PHP Reference ยท String Functions
PHP strlen() function
Reference for PHP strlen(): count the bytes in a string, why UTF-8 characters can count as several bytes, empty strings, and when to use mb_strlen() instead.
strlen() returns the number of bytes in a string. For plain ASCII text that equals the number of characters, but PHP strings are byte sequences with no built-in encoding, so a character such as รฉ or ๆฅ that takes several bytes in UTF-8 counts as several.
When you need the number of characters (what a user would count), use mb_strlen().
<?php echo strlen("Hello"); // 5 echo strlen(""); // 0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
strlen(string $string): int
| Name | Description |
|---|---|
$string |
The string to measure. |
Return value: the length in bytes, as an integer. An empty string gives 0.
Errors: a TypeError is thrown for arrays and objects without __toString(). Passing null is deprecated since PHP 8.1 (it still returns 0). Under declare(strict_types=1), passing an int or float throws.
Usage notes
- Bytes, not characters. In UTF-8, ASCII letters take 1 byte, most accented Latin letters 2, most CJK characters 3 and emoji 4. Use
mb_strlen()for characters. - Database limits.
VARCHAR(255)limits are in characters in MySQL, so validate withmb_strlen()there;strlen()is the right choice for byte limits such as upload sizes or binary data. - Constant time. PHP stores the length with the string, so
strlen()does not scan it and is safe to call in loop conditions. The compiler can even inline it. - Not for arrays. Use
count()for arrays. - Passing null raises a deprecation notice in PHP 8.1+; cast or check first.
- Whole-value checks. Use
$s === ""orstrlen($s) === 0for emptiness;empty("0")istrue, which surprises people. - Grapheme clusters. Even
mb_strlen()counts code points, so a flag emoji or letter with a combining accent can still count as more than one.
Related
mb_strlen(),substr(),str_pad(),str_word_count()- Lessons: Strings, Multibyte strings