PHP count_chars()Functions

PHP String 参考手册PHP String Reference Manual

Examples

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

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

Run Example »

Definition and Usage

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


Syntax

count_chars(string,mode)

Parameters Description
string Required. Specifies the string to be checked.
mode Optional. Specifies the return mode. Default is 0. There are the following different return modes:
  • 0 - Array, with ASCII value as key name and number of occurrences as key value
  • 1 - Array, with ASCII value as key name and number of occurrences as key value, only listing values where the number of occurrences is greater than 0
  • 2 - Array, with ASCII value as key name and number of occurrences as key value, only listing values where the number of occurrences is equal to 0
  • 3 - String, with all the different characters that have been used
  • 4 - String, with all the different characters that have not been used

Technical Details

Return Value: Depends on the specifiedmodeparameters.
PHP Version: 4+


More Examples

Example 1

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

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

Run Example »

Example 2

In this example, we will use count_chars() to check the string with the return mode set to 1. Mode 1 will return an array, with ASCII value as key name and number of occurrences as key value:

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

Run Example »

Example 3

Another example of counting the number of times ASCII characters occur 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> was found $value time(s)<br>";
}
?>

Run Example »


PHP String 参考手册PHP String Reference Manual Other Extensions