PHP strlen() function
Syntax
strlen ( string ) ;
Parameter | Description |
String | String to check (Required) |
Definition
It returns number of character in a string.
Usage
Strlen function is used to find the length of a string.
strlen() often comes in useful if you want to validate a string to make sure it ’ s the correct length. For example, the following code makes sure that the string variable $name must be 5 characters long.
Example of strlen function
<?php $name="John"; if ( strlen( $name ) != 5 ) { echo "Correct input."; } else { echo "incorect input"; } ?>
Output
You can validate form by using strlen function with the help of conditional statement like if else.
Example of strlen function
<?php echo "Length of sting:"; echo strlen("welcome to PHP"); ?>
- Example
- Run
In above example directly pass the string into the strlen function and print the result.
More example of strlen function
<?php $a="Hypertext pre-processor"; echo $a."
"; echo "Number of character in this string with white space and special symbol: "; echo strlen($a); ?>
- Example
- Run
$a is a string variable that hold a string with white spaces and special symbol and pass it to the strlen function that return the number of character including white spaces and special symbol.
Note: Whitespaces are also a part of the string.