How to Measure the Length of a String in PHP


We will show you how using PHP, you can measure the length of a string to find out how many characters are in the string.

This can be useful in very applications such as when a user is typing a string into a form field, such as a password, and the password must be between a range of characters, such as between 6 and 25 characters. We measure the string that the user enters when registering a password. If the password is less than 6 characters or greater than 25 characters, we can send a message, stating to the user that this password is not acceptable.

PHP Code to Measure the Length of a String

To meausre the length of a password in PHP, we use the strlen() function in PHP, following the format below:

Actual PHP Output

The string length of the fruit cantaloupe is 10

To find the length of a string in PHP, all we must do is put the string inside of the strlen() function either directly by the string being enclosed in double quotes ("") or by variable.

Since the word 'Cantaloupe' has 10 letters, the PHP strlen function will return '10' as output.

String Length Measurer

Enter any string into the text box below. Once you enter a string and press the 'Find Length of String' button, it will output the length of that string in the text box right beneath it.

Enter string:

Length of String:

This text box, above, again takes the string and computes its length through the strlen() function.


The HTML code to create the above text boxes and submit button are:

PHP Code

The PHP code to compute the length of the entered string is:

PHP extracts the information entered into the text box and assigns it to the $string variable. It then uses the strlen() function to find the length of this string, which it stores inside of the $length variable. This variable is then output into the second text box to show the length of the entered string.

HTML Comment Box is loading comments...