Get the length of a string in PHP

How to get the length of a string using PHP

Posted by Lukee Beeno on April 12, 2023

Get the length of a string in PHP

How to get the length of a string using PHP

Posted by Lukee Beeno on April 12, 2023

In this demonstation you will be shown how to get the length of a string using the strlen() function in PHP. 

The strlen() is a built-in PHP function that takes a string as a parameter and returns its length. All the white spaces and special characters are calculated as part of the length.

Here is how you can get the lenght of a string in PHP.

  • Use the strlen() method to get the length of a string
  • Spaces within the string are counted as well

In general, we first assign the string  to the variable. Then we call the strlen() function with the  variable as its argument. Finally, we use the echo statement to print out the length of the string.

Here is an example without white space:

$str = 'Hacking';
echo strlen($str); // Outputs: 7

As you can see above, a string is passed to the strlen() function as a parameter in order to return a result. 

Here is an example with space:

$str = 'Happy Hacking';
echo strlen($str); // Outputs: 13

The strlen() function will count the white space and special characters as part of the length of the string.

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question