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
?>/*w  w w  .  j  ava2s . co m*/

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