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); ?>
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:
|
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); ?>
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)); ?>
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>"; } ?>