In php, the strlen() function allows us to get number of characters and length of a string variable.

$variable = "I'm a variable";

echo strlen($variable);

//Output:
14

When working with string variables in our php programs, it is useful to be able to easily extract information about the values of the strings. In php, we can get the length of a string with the php strlen() function.

strlen() returns the length, or the number of characters, of a string.

To use strlen(), pass a string variable and strlen() will return the string length.

Below is a simple example in php of how to use strlen() to get the length of a string variable.

$variable = "I'm a variable";

echo strlen($variable);

//Output:
14

Examples of Using the php strlen() Function

strlen() is a very useful function and there are a number of examples of how we can use strlen().

One example is if you want to loop over the characters in a string. You can use range() and loop from 0 to the length of the string.

$variable = "this is a variable";

foreach(range(0,strlen($variable)) as $i) {
   // do stuff here
}

Another example of using the php strlen() function is if you want to get a substring of the last handful of characters.

Below is an example in php of how to get a substring of the last three characters using substr() and strlen().

$variable = "this is a variable";

$last_three = substr($variable, strlen($variable) - 3);

echo $last_three;

//Output:
ble

Hopefully this article has been useful for you to learn how to use the php strlen() function to find the length of string variables in your php programs.

Categorized in:

PHP,

Last Update: March 13, 2024