PHP Tutorial - PHP count_chars() Function


The count_chars() function returns an array containing the letters used in that string and how many times each letter was used.


PHP count_chars() function has the following syntax.

mixed count_chars ( string str [, int mode] )


If the mode parameter is 1, only letters with a frequency greater than 0 are listed; if the mode parameter is 2, only letters with a frequency equal to 0 are listed.


PHP count_chars() function returns the character count.


Get the caracter count

$str = "This is a test from"; 
$a = count_chars($str, 1); 

In that output, ASCII codes are used for the array keys, and the frequencies of each letter are used as the array values.

The code above generates the following result.

Example 2

The following code shows how to count char frequency.

   $sentence = "The rain in Spain falls mainly on the plain";
   // Retrieve located characters and their corresponding frequency.
   $chart = count_chars($sentence, 1); 

   foreach($chart as $letter=>$frequency)
      echo "Character ".chr($letter)." appears $frequency times<br />";

The code above generates the following result.