Hit enter after type your search item

How to use PHP strlen to get the string length with 5 examples

The strlen function of PHP

The strlen function is used to get the length of a string in PHP programs.

The function returns bytes unlike the general conception of returning the number of characters in the given string.

This is how you may use the strlen function to get string length:

The strlen PHP function may be useful for different scenarios, for example, the HTML div should display only a limited number of characters from the user’s feedback, which is stored in a database. You may get the length of string and do some programming to display only limited string.

An example of PHP string length by using strlen function

In this example, a simple string is created which is assigned to a string variable. After that, an int variable is used which is assigned the return value of strlen function for that string:

PHP string length

See online demo and code

This is how the PHP strlen function is used in above example:


The output of the above example is:

The length of string is :24

An example of having leading and trailing spaces in a string

The PHP’s string length method, strlen, will treat leading or trailing spaces as length while returning the total length of the given string. In this example, a leading and trailing space is added in the above example’s string. See what length is returned:

PHP strlen

See online demo and code

You see, it returned 26 because two spaces were added in the string.

What happens if you use arrays in strlen function

The PHP strlen function works with strings. If you use an array in the strlen function, it will return null and emits a warning message.

See the output when an array is used in the function:

PHP strlen arrays

See online demo and code

You see, it returns null and as such it is just a warning, the string in echo statement displayed and the program did not crash.

What if an array element is specified in strlen function

This time, an array is used in the strlen method, however, an element is given there with its index number. The following array is created:

$arr = array (‘This’,’is’,’strlen’,’Tutorial’);

After that, the strlen method is used and see the output:

PHP strlen array element

See online demo and code

The third element in the array is:


As such, its length is 6, so strlen method returned the same. This is how the strlen method is used with array element:


An example of using integer in strlen function

If you give an integer variable in the strlen function to get the length of an integer variable, it will return its length. The following example demonstrates that where 9 digit integer is given:

PHP strlen integer

See online demo and code

You see, the length of an integer variable with value 123456789 is returned as 9:

This div height required for enabling the sticky sidebar