Definition and Usage
- PHP Version
- 4+
The strlen() function returns the length of a given string as a number.
The length returned by the strlen() function is the number of bytes (in bytes),
and for multibyte strings such as Chinese, Japanese, and Korean (CJK) characters, it may not return the actual character count of the string.
This function is used to determine the length of strings composed of single-byte characters, such as English letters and numbers.
To determine the length of multibyte strings such as Chinese, Japanese, and Korean (CJK) characters, use the mb_strlen() function.
Basic Example
$str_1 = 'abcdef1234';
var_dump(strlen($str_1)); // int(10)
/* Spaces are included in the string length */
$str_2 = 'abc def';
var_dump(strlen($str_2)); // int(7)
$str_3 = ' abc def ';
var_dump(strlen($str_3)); // int(9)
$str_4 = ' ';
var_dump(strlen($str_4)); // int(1)
/* Empty string */
$str_5 = '';
var_dump(strlen($str_5)); // int(0)
/* Boolean values (non-string type) */
var_dump(strlen(true)); // int(1)
var_dump(strlen(false)); // int(0)
Syntax
strlen(string $string): int
Parameters
$string |
The string whose length will be measured. |
|---|
Return Values
Returns the length of the string in bytes (in bytes) as an integer.
Things to Keep in Mind
When using the strlen() function, the returned value may not always behave as expected depending on the type of the parameter.
Boolean Parameter Case
The strlen() function also works with boolean values even though they are not strings.
trueis converted to the string'1', which has a byte length of 1.falseis converted to an empty string (''), which has a byte length of 0.
$str_1 = true;
var_dump(strlen($str_1)); // int(1)
$str_2 = false;
var_dump(strlen($str_2)); // int(0)
When the Parameter Is a Multibyte String Such as CJK Characters
English letters and numbers are represented using 1 byte, whereas characters such as Chinese, Japanese, and Korean (CJK) are represented using 2 or more bytes.
Characters encoded with 2 or more bytes are referred to as multibyte characters.
The length returned by the strlen() function is the number of bytes (in bytes), not the number of characters.
$str = 'こんにちは'; // Multibyte string (Japanese)
var_dump(strlen($str)); // int(15)
As shown in this example, multibyte strings such as CJK characters may return a value that differs from the actual number of characters.
To determine the length of multibyte strings such as CJK characters, use the mb_strlen() function.
$str = 'こんにちは'; // Multibyte string (Japanese)
var_dump(mb_strlen($str)); // int(5)
References
See Also
- PHP mb_strlen() Function – Multibyte-Safe Alternative to strlen()
- PHP count() Function – Check Array Length
- PHP trim() Function – Removing Whitespace or Specified Characters from Both Ends of a String
- PHP substr() Function – Slice Strings by Position and Length
- PHP strpos() Function – Find First Substring Index
- PHP stripos() Function – Find First Substring Index (Case-Insensitive)