PHP count_chars() function is used to count the number of times each ASCII character occurs in a string.
Syntax
count_chars($string, return_mode);
Parameters
- $string(required): It is the input string.
- return_mode(optional): This parameter defines an operation that needs to be performed on the string. It takes values 0, 1, 2, 3, 4.
- 0: If this mode is chosen, the function will return the array with key-value pairs whose keys are ASCII values. The corresponding values will be several occurrences of that ASCII 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 used byte-values is returned.
- 4: A string containing all not used characters from the input string.
Return value
It returns an array or string depending on the return_mode as described above.
Visual Representation
Example 1: How to Use count_chars() function
<?php
$model = "MillieBobbyBrown";
print_r(count_chars($model, 3));
Output
BMbeilnorw
Returns a string containing all unique characters (in mode 3) from the input string.
Example 2: Using mode 4
<?php
$model = "MillieBobbyBrown";
print_r(count_chars($model, 4));
Output
!"#$%&'()*+,-./0123456789:;<=>?@ACDEFGHIJKLNOPQRSTUVWXYZ[\]^_`
acdfghjkmpqstuvxz{|}~������������������������������������������
��������������������������������������������������������������������������������������
Returns a string containing all the bytes not used in the string (in mode 4).
Example 3: Using mode 1
<?php
$model = "MillieBobbyBrown";
$strArray = count_chars($model, 1);
foreach ($strArray as $key=>$value)
{
echo "The character'".chr($key)."' was found $value time(s)". "\n";
}
Output
The character'B' was found 2 time(s)
The character'M' was found 1 time(s)
The character'b' was found 2 time(s)
The character'e' was found 1 time(s)
The character'i' was found 2 time(s)
The character'l' was found 2 time(s)
The character'n' was found 1 time(s)
The character'o' was found 2 time(s)
The character'r' was found 1 time(s)
The character'w' was found 1 time(s)
The character'y' was found 1 time(s)
When used in mode 1, obtains the frequency of each character present in the string $model.