Skip to content

Difference Between Grapheme_strlen() And Iconv_strlen() Functions In PHP

In this article, you will be learning the difference between grapheme_strlen() and iconv_strlen() functions in php. The grapheme_strlen() function is used to evaluate the length of a given string in grapheme units. A grapheme unit is the smallest unit used in programming language which includes numerical digits, chinese characters, alphabets and other symbols.

The iconv_strlen() function is used to display the number of characters in a string depending upon the value of the defined character.

Both of these functions are described below in detail.

GRAPHEME_STRLEN() FUNCTION

Syntax : grapheme_strlen($str);

Result/ Return Value : There are two possible outcomes using this function.

  1. On the successful execution of the function, the length of the given string(integer value) in grapheme unit will be returned.
  2. If the given string is left empty, 0 will be returned.
php-graph-1024x263

Example : A simple example of grapheme_strlen() function is shown below.

php graphoutput-1024x141

Output : You will get the following output after running the above php script. Here we have taken a string ‘absca\xCC\x8Ao\xCC\x88a\xCC\x8A’ whose value is stored in the variable $int using grapheme_strlen() function. Cleary, you will get 7 as the output as shown in the image below.

ICONV_STRLEN() FUNCTION

Syntax : iconv_strlen($str, $charset);

Two parameters are used in this function which are discussed below.

  • $str- It represents the string whose length is to be determined.
  • $charset- This string parameter represents the value of character encoding. UTF-8 is the most common charset value used in this function. If we exclude the $charset parameter, the function will take the value of internal character encoding.

Result/ Return Value : It will return an interger value corresponding to the length of the string showing number of characters.

php-icon-1024x365

Example : We have shown below a simple example of iconv_strlen() function.

php-iconoutput-1024x263

Output : The following output will be generated after running the above php script. Here, we have taken ‘W3training School’ as a string whose length is to be determined. We have then applied three methods to find the number of characters in a given string namely mb_strlen(), strlen(utf8_decode()) and iconv_strlen(). All these functions will display the number of characters in the string ‘W3training School’ which is equal to 17(including the space between W3training and School) as shown in the image below.

Above, we have tried to provide you the best possible description of the difference between grapheme_strlen() and iconv_strlen() functions in php. Hope this post helped you eliminating your complications. For more updates and related information regarding php, stay connected to our php blogs. 

Facebook
Twitter
LinkedIn
Pinterest