Last Updated:

PHP : Get the string length


There are two functions to count the number of characters in a string: strlen and mb_strlen.

For counting with a latin alphabet character in a string, both functions are suitable, regardless of the encoding of the text.

For the Cyrillic alphabet, you must use the mb_strlen function, since the second parameter can be used to specify the encoding type.

Cyrillic characters using the mb_strlen function will be counted more correctly with the specified encoding utf-8.

Sample source code.

The result of the work of functions with the Cyrillic and Latin alphabet:


The result of the code:

// source lines
$str1 = "Verification text";
$str2 = "Verification text";
// determine the length of Cyrillic and Latin strings using strlen
$str_len1 = strlen($str1);
$str_len2 = strlen($str2);
// determine the length of Cyrillic and Latin strings using mb_strlen
$mb_str_len1 = mb_strlen($str1, 'utf-8');
$mb_str_len2 = mb_strlen($str2, 'utf-8');
// display the result in Latin
echo 'Latin: <br/>';
echo "strlen: $str_len1<br/>";
echo "mb_strlen: $mb_str_len1";
echo '<br />';
// result output with Cyrillic
echo 'Cyrillic: <br/>';
echo "strlen: $str_len2<br/>";
echo "mb_strlen: $mb_str_len2";


Latin:
strlen: 17
mb_strlen: 17
Cyrillic:
strlen: 35
mb_strlen: 18