PHP string length: 3 examples to use strlen function

PHP string length function

In many scenarios, you will need to know the total number of characters in strings of your PHP program. For example, notifying the users how many characters are used in a text box, from the given limit in your program.

See an example of getting string length

In twitter, for example, it only allows 140 characters long tweets. Although this could be done at the client end by using the JavaScript or some other method, you can use string length function, strlen() to know the string length in PHP program.

Example of using strlen()

The following example uses the PHP strlen() function to display the total number of characters in a given string.

PHP string length

Experience this example online



This will output:

5

String length PHP example with a variable

The following example displays total string length in a PHP variable by using the strlen method.

PHP strlen method

Experience this example online



This will be the output: 26

Spaces are also counted, as this comes under the characters.

Another example of PHP strlen

Experience this example online



In the above example, the string length is assigned to an integer variable that you can use in the if condition, to check and compare with your limit or whatever the requirement may be.

 

Useful links: PHP Strings | String Replace


Was this article helpful?

Related Articles

Leave A Comment?