PHP count_chars() Function

Example

Returns a string containing all the different characters used in "Hello World!" (mode 3):

<?php
$str = "Hello World!";
echo count_chars($str,3);
?>

Run Examples

Definition and Usage

The count_chars() function returns information about the characters used in a string (for example, the number of times an ASCII character appears in the string, or whether a character has been used in the string).

Syntax

count_chars(string,mode)
Parameter Description
string Required. Specifies the string to be checked.
mode

Optional. Specifies the return mode. The default is 0. The following are different return modes:

  • 0 - Array, ASCII value as key name, occurrence count as value
  • 1 - Array, ASCII value as key name, occurrence count as value, only list values with occurrence count greater than 0
  • 2 - Array, ASCII value as key name, occurrence count as value, only list values with occurrence count equal to 0
  • 3 - String, with all used different characters
  • 4 - String, with all unused different characters

Technical Details

Return Value: depends on the specified mode Parameters.
PHP Version: 4+

More Examples

Example 1

Returns a string containing all unused characters in "Hello World!" (pattern 4):

<?php
$str = "Hello World!";
echo count_chars($str,4);
?>

Run Examples

Example 2

In this example, we will use count_chars() to check the string, the return pattern is set to 1. Pattern 1 will return an array, where the ASCII value is the key name and the occurrence count is the value:

<?php
$str = "Hello World!";
print_r(count_chars($str,1));
?>

Run Examples

Example 3

Another instance of counting the number of times an ASCII character appears in a string:

<?php
$str = "PHP is pretty fun!!";
$strArray = count_chars($str,1);
foreach ($strArray as $key=>$value)
  {
echo "The character <b>'".chr($key)."'</b> is found $value times.<br>";
  }
?>

Run Examples