PHP count_chars()Functions
Examples
Returns a string containing all the different characters used in "Hello World!" (mode 3):
<?php
$str = "Hello World!";
echo count_chars($str,3);
?>
$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:
|
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);
?>
$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));
?>
$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>";
}
?>
$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 Reference Manual Other Extensions