During the web development process, there is a time you may find yourself having the need to determine the number of characters that are present in a particular string. This is most common when in case you want to check whether a certain condition is met so that you can trigger the next action, for example, you may want to ask a user to enter his name and you may want to confirm whether his name has more than three characters. It is also used to maintain uniformity, for example, in eCommerce websites, product descriptions while listing products, you can limit the number of characters you want to display.
In this article, we shall show how to calculate the length of a string in PHP. Calculating the length is the same as getting the size of a string or counting the number of characters present in a string or variable. The result is always a number when you calculate the length.
To calculate the length of a string in PHP, we use strlen() function which is an inbuilt function provided by the PHP language.
The syntax is as shown below
<?php
strlen("string to calculate length");
?>
The function takes a string as a parameter and returns the length as a number. It calculates the length of the string including all the whitespaces and special characters.
Example 1
<?php
//the string to calculate length is SolutionSpace
echo strlen("SolutionSpace");
?>
The result will be
13
When you add a white space inside a string and calculate its length, the result will be different since the white space is also counted as a character.
Example 2
<?php
//the string to calculate length is Solution Space
echo strlen("Solution Space");
?>
The result will be
14
To ensure you get the correct length of the string, you have to countercheck the existence of white spaces and special characters
Example 3
<?php
//the string to calculate length is @Solution Space !
echo strlen("@Solution Space !");
?>
The result will be
17
You can also define the string in a variable and include the variable as the parameter in the strlen() function
Example 4
<?php
//the string to calculate length is @Solution Space !
$string="@Solution Space !";
echo strlen($string);
?>
The result will be
17
If the string is empty, the strlen function will not return an error or null, the function is designed in a way it will return a number so the result will be 0;
Example 5
<?php
//the string to calculate length is ""
$string="";
echo strlen($string);
?>
The result will be
0
In a scenario where you have html tags in the string, the following example can guide you
Example 6
<?php
//the string to calculate length is "<p>This is a paragraph</p>"
$string="<p>This is a paragraph</p>";
echo strlen($string);
?>
The result will be
26
In the above article, hope you have learned how to calculate the length of a string in PHP using the strlen function. The examples we have used are the simplest examples you will come across, so its better you practice using any data you come across even the one stored in the database.