How to find the length of a string in PHP

How to find the length of a string in PHP

Sometimes we need to count the string length to meet some condition in the application. In PHP we have strlen() function to find the length of a string in the word or paragraph.

Let’s take an example, we need to run the loop in the application on the basis of string length, so here we do not know the length of the string and we can’t run the loop until we have a definite loop count. So in this case we can use strlen() function to find the length of a string the PHP. Then we would be able to get the loop count and we can simply perform the action. There could be many possible ways where we would require strlen() functions.

We can simply use the PHP strlen() function to count the length of the given string. It takes one argument and returns its length. It counts the string length including white space and special characters.

Following is the syntax of strlen() function.

Syntax:

strlen($string)

Parameters:  The strlen() function accepts only one parameter as a string.

Return Value: strlen() function returns the length of the string including white space and special characters.

<?php 
    $str = "Atcodex.com"; 
    echo strlen($str); 
?>  

Output

11

In the above example, we have $str variable, when we pass the variable in strlen() function, the function will return us the length of the $str value.

Conclusion:

Now we know how easy is to find the length of a string in PHP using the strlen() function. We can invoke this in many situations as we have mentioned in the above paragraph.

PHP provides us many functions as we discussed, and that makes it very easy to learn. We have many inbuilt functions and methods in it and that provides the developer a very easy way to perform any task, That I think a plus point of the language.

You can also check How to open the numeric keyboard in mobile and validate the length

Spread the love