PHP count_chars() Function

PHP count_chars() Function

The count_chards() function in PHP is used to return information about characters in a string.

Syntax

count_chars ( string $string [, int $mode = 0 ] )

Parameter

string(required)- This parameter represents the string to be checked.

mode(optional)- It specifies the return modes

Return

This function returns one of the following values depending on the mode parameter:

  • 0 - an array with the byte-value as key and the frequency of every byte as value.
  • 1 - same as 0 but only byte-values with a frequency greater than zero are listed.
  • 2 - same as 0 but only byte-values with a frequency equal to zero are listed.
  • 3 - a string containing all unique characters is returned.
  • 4 - a string containing all not used characters is returned.

Example 2

<?php
// initializing the string
$str = "Hello World!"; 
// printing the string
echo "Original string: ".$str;  
// passing mode value=3
$CountChar = count_chars($str,3); 
// will return a string containing all unique characters is returned. 
echo "\nAfter using 'count_chars()' function\nNew string:".$CountChar;
?>   

Output

Original string: Hello World!
After using 'count_chars()' function
New string: !HWdelor   

Example 3

<?php
// initializing the string
$value = "I love India.";  
foreach (count_chars($value, 1) as $i => $int) {  
   echo "There are $int count of \"" , chr($i) , "\" character in the string.\n";  
}  
?> 

Output

There are 2 count of " " character in the string.
There are 1 count of "." character in the string.
There are 2 count of "I" character in the string.
There are 1 count of "a" character in the string.
There are 1 count of "d" character in the string. 
There are 1 count of "e" character in the string.
There are 1 count of "i" character in the string.
There are 1 count of "l" character in the string.
There are 1 count of "n" character in the string.
There are 1 count of "o" character in the string.
There are 1 count of "v" character in the string.