PHP strlen is an inbuilt Function in PHP. It takes a string as parameter and returns it’s length. Also, it calculates the length by including all whitespaces and special characters in the string. In this article, we will discuss the PHP strlen Function. Also, we will discuss a few examples of using it.
Note: The function returns the number of bytes rather than the number of characters in the string.
integer strlen (string);
The PHP strlen Function expects only one parameter. The string whose length you want to calculate is passed as the parameter to the function. If you pass an array to the function, then it emits an E_WARNING error.
Let’s discuss a few examples of using the PHP strlen Function to calculate the length of string.
Example 1: Simple String
<?php $string = 'Concatly'; echo strlen($string); /* 8 */ ?>
In the above example, the function returns the length of string.
Example 2: Whitespaces
<?php $string = 'Bringing Knowledge Together'; echo strlen($string); /* 27 */ ?>
Similarly, the PHP strlen function includes all the whitespaces while calculating the length of string. Each whitespace is counted as 1 character (or 1 byte).
Example 3: Special Characters
<?php $str = "\n concatly ;"; // here '\n' has been counted as 1 echo strlen($str); //12 ?>
In the above example, you can notice that the function treats the special character (‘\n’) as 1.
Example 4: Empty String or null
Similarly, the function returns 0 for an empty string or null character.
<?php echo strlen(""); // 0 echo strlen(null); // 0 ?>
However, it should not be used to check whether a string is empty or null because it returns 0 in both cases.
In conclusion, we discussed the strlen function in this article. It calculates the string length in PHP. You can read more about it on Official PHP Documentation. Also, you can read about more PHP String Functions on Concatly.
Vishesh is currently working as a Senior Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.