PHP Tutorial - PHP count_chars() Function






Definition

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

Syntax

PHP count_chars() function has the following syntax.

mixed count_chars ( string str [, int mode] )

Parameter

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.

Return

PHP count_chars() function returns the character count.





Example

Get the caracter count


<?PHP
$str = "This is a test from java2s.com."; 
$a = count_chars($str, 1); 
print_r($a); 
?>

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.


<?php
   $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.