Quick Reach
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.
Experience this example online
1
2
3
4
5
|
<?php
echo strlen("Hello");
?>
|
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.
Experience this example online
1
2
3
4
5
6
7
|
<?php
$string_length = "I am testing string length!";
echo strlen($string_length);
?>
|
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
1
2
3
4
5
6
7
|
<?php
$string_length = "I am testing string length!";
$int_Strlength = strlen($string_length);
?>
|
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
Leave A Comment?