Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

strlen: a string length in bytes

strlen counts the bytes of a PHP string, not the characters visible on screen. This measures data size, but does not always measure text length for a user.

Version: PHP 8.4

Syntax

strlen(string $string): int

The result of strlen("ABC") is 3, and an empty string has length 0. Spaces and a zero byte also count. PHP does not end a string at the first zero byte, so strlen("A\0B") gives 3.

In UTF-8, the letter é occupies two bytes. Similar-looking text made from e and a separate accent occupies three. Bytes, Unicode code points and grapheme clusters are different measures; strlen alone does not validate encoding.

In the example, declare(strict_types=1) disables implicit acceptance of numbers in place of a string. An invalid type raises TypeError. Check the input type instead of assuming that every value will turn itself into text.

Use strlen for byte limits. For text limits, decide whether you mean code points or user-perceived characters. mb_strlen needs the mbstring extension and accepts an encoding argument; specify UTF-8 when that is your input encoding. grapheme_strlen needs intl and valid UTF-8 input, with no encoding parameter. The example works without these extensions and deliberately measures bytes only.

Examples

<?php
declare(strict_types=1);

echo strlen(""), " ", strlen("A\0B"), "\n";
echo strlen("\u{00E9}"), " ", strlen("e\u{0301}"), "\n";
try {
    strlen(42);
} catch (TypeError $error) {
    echo "TypeError\n";
}

Result

0 3
2 3
TypeError

Sources