Introduction

You can find out its length with the strlen() function.

This function takes a string value as an argument, and returns the number of characters in the string.

For example:

Demo

<?php

$myString = "hello";
echo strlen( $myString ) . " \n "; // Displays 5
echo strlen( "goodbye" ) . " \n "; // Displays 7
?>/*from w w w  .  j  av a2 s .c om*/

Result

strlen() is useful when looping through all the characters in a string, or to validate a string to make sure it's the correct length.

For example, the following code makes sure that the string variable $year is 4 characters long:

if ( strlen( $year ) != 4 ) {
    echo "The year needs to contain 4 characters. Please try again.";
}else {

}
// Process the year

Related Topic