Finding the length of a string in PHP is easy using the appropriately named strlen function. This PHP function is one of the more readily understood functions as it takes only a single parameter, which is the string to check the length of.
Finding the length of a string is useful in situations where the next task we will be doing requires us to know the length of the string that we are working with, such as finding substrings.
Whatever your need, the PHP string length tutorial below will get you up to speed on finding the length of strings in PHP.
The syntax for the strlen function is shown below:
$number = strlen($string);
Where $number will be an integer containing the length of the string, and $string is the string which we want to find the length of.
The example below will show how we determine the length of a string using PHP.
<?php // create a string $string = "I love Tutorial Arena so much"; // find the length $length = strlen($string); // output the length to the screen echo $length; ?>
If we ran that code, we would get the output:
That is, 29 characters made up the string which was passed to the function. If we actually count the amount of characters contained in the string "I love Tutorial Arena so much", we see that it does indeed contain 29 characters. Remember that spaces are characters as well!
The PHP strlen function is very useful in cases where we need to know the exact size of a string before we can perform another operation on it.
This operation may be to simply write the string to a file or to use PHP substring to break it into pieces. It would also be useful in a situation where we would want to know if we should show the entire contents of a string to the user, or break it off and show them a "Read more" link.
Whatever your goal is, the strlen function comes in handy.
We hope this tutorial on finding the length of a string in PHP was enlightening. Please move on to another PHP tutorial in our series.