The purpose of the strlen() function is to return the length of the passed string as an integer. Embedded control characters and null characters are counted in the length. If the string is empty or a null value is passed, the function returns 0.


int strlen( string $str )


String whose length is to be returned.

Return Value

Length of the string passed as an argument.


1. Compute String Lengths

This example uses strlen() to compute the length of various strings. The string on line 3 has a terminating newline (\n). The string on line 4 has an embedded tab (\t). The string on line 5 contains only a carriage return (\r) and a newline (\n).

echo 'strlen("Hello, world!"): '    . strlen("Hello, world!")    . "\n";
echo 'strlen("Hello, world!\n"): '  . strlen("Hello, world!\n")  . "\n";
echo 'strlen("Hello,\tworld!\n"): ' . strlen("Hello,\tworld!\n") . "\n";
echo 'strlen("\r\n"): '             . strlen("\r\n")             . "\n";

The output of the program above is shown below. Escape sequences such as \n, \t, and \r are each counted as one character.

strlen("Hello, world!"): 13
strlen("Hello, world!\n"): 14
strlen("Hello,\tworld!\n"): 14
strlen("\r\n"): 2

2. Empty Strings, NULL Characters, and Null Expressions

This example passes an empty string on line 2, a string with a single null character (\0) on line 3, and a null expression on line 4.

echo 'strlen(""): '   . strlen("")   . "\n";
echo 'strlen("\0"): ' . strlen("\0") . "\n";
echo 'strlen(null): ' . strlen(null) . "\n";

As can be seen from the output below, the empty string (two quotes with nothing between) has a length of 0. However, a string with a single null character (\0) has a length of 1 as the null character is counted as an actual byte. Finally, the null-valued expression has a length of 0.

strlen(""): 0
strlen("\0"): 1
strlen(null): 0

This might make you wonder how you can tell if a string variable has a null value versus a null string….

[insert example of this]

3. Numbers as Strings

In this example, numeric values are passed to strlen(). In line 2 an integer is passed and in line 3 a float is passed.

echo 'strlen(100): '    . strlen(100)    . "\n";
echo 'strlen(12.345): ' . strlen(12.345) . "\n";

When a number argument is passed to a string parameter, PHP converts it to a string. So in line 2 below, the integer 100 is passed as the string “100”, which has a length of 3. In line 3, the float 12.345 is passed to strlen() as “12.345” and so has a length of 6 (the ‘.’ counts as a separate character).

strlen(100): 3
strlen(12.345): 6

See Also