PHP 8 reference · String Functions
PHP strlen() Function
Return the length of a string in bytes. Multibyte characters such as é count as several bytes; use mb_strlen() to count characters.
PHP 8 Since 4.0
Syntax
strlen(string $string): int
Parameters
| Parameter | Description |
|---|---|
string |
The input string. |
Return value
The number of bytes, as an int.
Examples
<?php
echo strlen("camel"), "\n";
echo strlen(""), "\n";
echo strlen(" hi "), "\n"; // spaces count too
Output
5 0 6
<?php
$word = "café";
echo strlen($word), "\n"; // 5: é takes 2 bytes in UTF-8
echo mb_strlen($word), "\n"; // 4 characters
Output
5 4
Common mistakes
strlen()counts bytes, not characters. For user-facing UTF-8 text usemb_strlen().- Use
count()for arrays;strlen()on an array throws aTypeError. - Since PHP 8.1, passing
nullis deprecated. Writestrlen($name ?? "")when a value can be missing.
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
len()· Pythonstring.length· JavaScript
Related
mb_strlen()· Return the number of characters in a string, counting é or 日 as one character. The UTF-8-safe version of strlen().str_word_count()· Count the words in a string, or return them as an array. Words are runs of letters plus ' and -; digits split words.count()· Return the number of elements in an array or Countable object. With COUNT_RECURSIVE it also counts nested elements.- PHP Strings · tutorial