Last updated on October 11, 2023
The strlen() function is used to find the length of a string PHP. It takes a string as a parameter and returns the length in an integer. It is supported by PHP 4, 5, 7 and 8.
Syntax
strlen($string);
Parameters
It has a required parameter that refers to the string that words needed to count.
Example 1
Let’s find the length of the string “programming” through the strlen()
function. To do that, we need to pass the string into the function.
echo strlen("programming");
// Output: 11
In this example, a string that contains programming is passed as an argument into the strlen()
function. In the output, the strlen()
function returned 11 which is because programming contains 11 alphabetic letters.
Further, let’s check the data type of return value. We can use PHP built-in function var_dump()
for checking the data type.
var_dump(strlen("programming"));
// output: int(11)
In the line of code above, we used the var_dump()
function to check the data type of the return value from the strlen()
function, which is an integer.
Example 2
In the previous example, we found a string’s length containing a single word. Now let’s find out the length of the string that contains a phrase.
echo strlen("programming is best");
// Output: 19
In this example, a string that contains words and white spaces is passed into the strlen()
function to find the length. In the output it returns 19 which means the strlen()
function counts the alphabetic letters along with white spaces.
Conclusion
This article demonstrates how to find out the string length in PHP. It uses the PHP built-in function strlen()
that takes the string as an argument and returns the length of the string.