In this article, we will talk about the difference between strlen() and mb_strlen() functions in php. These string functions are used to determine the length of a given string. Function strlen() is used when we require the string length showing a number of bytes whereas function mb_strlen() is used when we require the string length showing number of characters.
The mb in the mb_strlen() function stands for multibyte.
These functions are described below in detail.
STRLEN() FUNCTION
Syntax : strlen($str);
A single parameter is used in this function i.e, $str which represents the string whose length is to be determined.
Result/ Return Value : On the successful execution of strlen() function, the length of the given string will be returned. And if the string parameter is left empty, 0 will be returned.
Error : This function cannot be used to find the length of an array. It will generate anE_WARNING error and Null will be returned.
Example 1 : An example of strlen() function to find the length of the string in number of bytes is shown below.
Output 1 : You will get the following output after running the above php script. Here, we have used ‘W3training School’ as the string whose length is to be determined. We have taken a variable $res to store the value of the string by using strlen() function. The output 17 represents the length of the string in number of bytes.
Example 2 : An example of strlen() function generating an error when used for an array is shown below.
Output 2 : The following output will be generated after running the above php script . Here, we have used an array of elements whose length is to be determined and stored this value in a variable $abc. When this variable is executed by using the strlen() function, a warning is generated as shown in the image below. Clearly, this function cannot be used to determine the length of an array of elements.
MB_STRLEN() FUNCTION
Syntax : mb_strlen($str, $encoding);
Two parameters are used in this function.
- $str- The string whose length is to be determined.
- $encoding- This string parameter denotes character encoding that can have following values.
(1) UTF-8
(2) ASCII
(3) JIS
(4) CP50220
(5) 8bit
(6) 7bit
(7) ISO-8859-1
(8) UCS-2
(9) BASE64
(10) Windows-1251 (CP1251), etc.
If this parameter is excluded, the function will use the internal value of character encoding.
Result/ Return Value : It will return the length of the given string showing number of characters when the character encoding is valid. It will return False when the character encoding is not valid.
Error : No influencing errors.
Example : A simple example of mb_strlen() function is shown below.
Output : You will get the following output by running the above php script. Here, the output 17 represents the number of characters in the string.
We have provided you the difference between strlen() and mb_strlen() functions in php. Hope you liked this article. For more information and updates, stay tuned to our php blogs