What does strlen() do?
strlen() returns the number of bytes in a string. For plain ASCII text that equals the number of characters, but UTF-8 characters such as é or emoji use 2-4 bytes each, so strlen() reports more than the visible character count.
Syntax
strlen(string $string): int
Parameters
$string- The string to measure. Spaces, tabs and newlines are counted like any other byte.
Return value
The length of $string in bytes as an int. An empty string returns 0.
strlen() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Basic string length
<?php
$text = "Hello, World!";
echo strlen($text) . "\n";
echo strlen("") . "\n";
echo strlen(" padded ") . "\n";
Output:
13 0 10
2. Bytes vs characters (UTF-8)
The é in "café" is two bytes in UTF-8. To count characters use mb_strlen() (mbstring extension) or, without mbstring, split the string with a Unicode-aware regex.
<?php
$word = "café";
echo strlen($word) . "\n";
echo count(preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY)) . "\n";
Output:
5 4
3. Validate the length of user input
<?php
function validateUsername(string $name): string {
$len = strlen(trim($name));
if ($len < 3) {
return "Too short ($len chars)";
}
if ($len > 16) {
return "Too long ($len chars)";
}
return "OK";
}
echo validateUsername("al") . "\n";
echo validateUsername("alice_92") . "\n";
echo validateUsername("a_very_long_username_here") . "\n";
Output:
Too short (2 chars) OK Too long (25 chars)
Common mistakes and gotchas
- Multibyte text:
strlen("café")is 5, not 4. Usemb_strlen($s)when you need the number of characters. - Passing null:
strlen(null)is deprecated since PHP 8.1 and emits "Passing null to parameter #1 ($string) of type string is deprecated". Usestrlen($value ?? ''). - Arrays: passing an array throws a
TypeError. Usecount()for arrays. - Checking for empty input:
strlen(trim($input)) === 0is clearer thanempty($input), which also treats"0"as empty.