In PHP, the primary length function is strlen(), which returns the number of bytes in a string. For multi-byte character sets like UTF-8, use mb_strlen() to count actual characters instead of bytes.
What strlen() Actually Returns
strlen() counts bytes, not characters. In ASCII, each character is one byte, so strlen("hello") returns 5. But for strings containing accented letters, emoji, or non-Latin scripts, each character may occupy 2, 3, or 4 bytes in UTF-8. For example:
strlen("café")returns 5 (c, a, f, é as 2 bytes, plus the é is 2 bytes: 4 bytes + 1 = 5)strlen("你好")returns 6 (each Chinese character is 3 bytes in UTF-8)strlen("😀")returns 4 (the emoji is 4 bytes)
This byte-based behavior is essential for functions that operate on raw binary data, like substr() or file handling, but it can be misleading when you want to display a string of a certain visual length.
Using mb_strlen() for Character Counts
The mb_strlen() function (part of the mbstring extension) counts characters, respecting the character encoding. Its signature is:
mb_strlen(string $string, ?string $encoding = null): int
If you omit the encoding, it uses the internal encoding set by mb_internal_encoding(). To be explicit and avoid surprises, always pass the encoding:
$text = "café";
echo mb_strlen($text, 'UTF-8'); // outputs 4
For UTF-8 strings, mb_strlen() returns the number of Unicode characters, which is what most people expect from a “length” function. Note that mb_strlen() counts combining characters separately (e.g., an “e” followed by a combining acute accent counts as 2 characters). If you need grapheme clusters (user-perceived characters), consider the grapheme_strlen() function from the intl extension.
How to Choose Between strlen() and mb_strlen()
Use strlen() when:
- You are working with binary data (e.g., file contents, encrypted strings).
- You need to know the exact byte size for protocol or storage limits.
- You are certain the string is ASCII-only.
Use mb_strlen() when:
- You are processing user input or text that may contain non-ASCII characters.
- You need to validate input length (e.g., maximum 140 characters for a tweet).
- You are counting characters for display or truncation.
If your application handles multiple languages, always prefer mb_strlen() with an explicit encoding. This avoids subtle bugs that appear only when a user enters accented or non-Latin characters.
Common Pitfalls and Misconceptions
One common mistake is assuming strlen() returns the number of characters. This leads to incorrect validation. For example, a form field that limits a name to 50 characters using strlen() would reject a 25-character name like “José” if the “é” is two bytes, because strlen("José") returns 5 instead of 4.
Another misconception is that mb_strlen() is always slower. While it does have overhead, the difference is negligible for typical web applications. The real cost is in loops over large arrays, but even then, correctness matters more.
Also, be aware that strlen() returns null if the string is not a valid UTF-8 sequence when using mb_strlen()? Actually, mb_strlen() returns the number of characters even if the string contains invalid byte sequences; it counts each invalid byte as one character. That can lead to unexpected counts. For strict validation, use mb_check_encoding() first.
Practical Examples with Validation
Suppose you are building a user registration form with a username field that must be 3–20 characters. Here is how you would validate it correctly:
$username = $_POST['username'] ?? '';
if (mb_strlen($username, 'UTF-8') < 3 || mb_strlen($username, 'UTF-8') > 20) {
echo "Username must be between 3 and 20 characters.";
}
If you used strlen(), a username like “ñandú” (5 characters) would be 6 bytes, and a 20-character limit would reject it if the byte count exceeds 20. Using mb_strlen() ensures the character count is as the user expects.
Another example: truncating a string to 50 characters for a preview. A naive substr() might cut a multi-byte character in half, producing a broken string. Instead, use mb_substr():
$excerpt = mb_substr($fullText, 0, 50, 'UTF-8');
This preserves whole characters.
Performance and Best Practices
For most applications, the performance difference between strlen() and mb_strlen() is negligible. However, if you are processing millions of strings, you can cache the encoding or use mb_strlen() only when needed. A common pattern is to check if the string is ASCII first:
if (preg_match('/^[\x00-\x7F]*$/', $string)) {
$length = strlen($string);
} else {
$length = mb_strlen($string, 'UTF-8');
}
But this adds overhead too. In practice, just use mb_strlen() for user-facing text. Also, ensure the mbstring extension is enabled (it is on most PHP installations). You can check with extension_loaded('mbstring').
Alternatives and Related Functions
PHP offers other length-related functions for different contexts:
count()– for arrays and Countable objects.sizeof()– alias ofcount().str_word_count()– counts words in a string.substr_count()– counts occurrences of a substring.grapheme_strlen()– counts grapheme clusters (user-perceived characters) if intl extension is installed.
For example, grapheme_strlen("é") returns 1 (the letter “e” with a combining accent is one grapheme), while mb_strlen() returns 2. If your application deals with emoji or complex scripts, consider using grapheme_strlen().
Frequently Asked Questions
Why does strlen() return 2 for a single accented character?
Because strlen() counts bytes, and in UTF-8, accented characters like “é” are encoded using two bytes. The function does not interpret the encoding; it simply counts the bytes in the string.
What is the default encoding for mb_strlen()?
It uses the value set by mb_internal_encoding(), which defaults to UTF-8 in most modern PHP installations. However, it is safer to always pass the encoding as the second argument to avoid relying on runtime configuration.
Can I use strlen() for JSON or database strings?
Yes, if you need the byte length for storage or protocol, strlen() is appropriate. For example, when checking the length of a serialized JSON string before storing it in a BLOB, byte count is what matters.
Is mb_strlen() available in all PHP versions?
It is available if the mbstring extension is installed, which is common but not guaranteed. You can check with function_exists('mb_strlen'). If not available, you can fall back to strlen() but only for ASCII-safe strings.
How do I count characters in a string with emoji?
Use grapheme_strlen() if you want each emoji to count as one character. For example, grapheme_strlen("👨👩👧👦") returns 1, while mb_strlen() returns 7 (because the family emoji is a sequence of multiple code points).
What is the difference between mb_strlen() and iconv_strlen()?
Both count characters according to an encoding. iconv_strlen() uses the iconv extension and may behave differently with invalid sequences. mb_strlen() is more common and better supported in PHP.
Related
- Redo Shortcut in Windows: Ctrl+Y and More
- Best Online Data Entry Sites That Actually Pay
- Google Sheets Query Multiple Criteria: How-To
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Round Excel Numbers to the Nearest Ten With a FormulaTo round a number to the nearest ten in Excel, use the ROUND function with -1 as its…
- Smartsheet SUMIF Examples for Everyday ReportsIn Smartsheet, SUMIF adds values in a sum range only when corresponding cells meet one condition. For example,…
- Python String Built-in Functions: Full List & ExamplesPython’s built-in string methods (often called “string functions”) let you manipulate text directly—searching, splitting, changing case, stripping whitespace,…
- Excel Formula for Multiple IFs (Nested IF & IFS)The direct answer: use the IFS function for most multiple-condition logic, or nest IF functions when you need…
- Remove Formula in Excel but Keep Data as Values SafelyTo remove formulas in Excel but keep the data they currently display, select the formula cells, copy them,…
- Excel Auto Fill Dates Based on a SequenceYes. In Excel for Microsoft 365 on Windows, enter a starting date and drag its fill handle down…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.