Definition and usage of PHP strlen
In PHP, we use strlen() method to find the length of the given string. This method takes the string as a parameter and provides the length of the input string as the return value. It considers all blank spaces and special characters as well while calculating the length of the string. If the input string is empty, then the return value will be 0.
This method is supported by PHP version 4 and above.
Below is the syntax to use PHP strlen() method.
string – the input string which is the mandatory parameter.
Return value – length of the input string
The below diagram will help you understand how PHP strlen() method finds the string length.
Example: How to find string length using strlen()
In the below program, the input string contains blank space. Hence strlen() method calculates the length including blank space
<html> <body> <?php $string = "PHP Script"; echo "Length of the string is:"; echo strlen($string); ?> </body> </html>
Output: Length of the string is:10
PHP program using strlen with special characters in an input string
Here, we have special characters and escape sequence included in the input string. The escape sequence(“\n”) is considered as a single character. This is another example of how to find the string length in PHP.
<html> <body> <?php echo "Length of the string is:"; echo strlen("\nPHP script!"); ?> </body> </html>
Output: Length of the string is:12
PHP program to calculate string length when the input string is empty
When the input string is empty, strlen() method returns string length as 0.
<html> <body> <?php echo "Length of the string is:"; echo strlen(""); ?> </body> </html>
Output: Length of the string is:0
In this tutorial, you have learned about how to calculate the length of the string using PHP strlen() method.