PHP count_char Function
The count_chars()
function in PHP is used to count the frequency of characters in a string. It returns an array where each key represents a unique character in the input string, and the corresponding value represents the number of occurrences of that character.
The syntax of the count_chars()
function is as follows:
count_chars(string $string, int $mode = 0): string|array
The function accepts two parameters:
$string
(required): The input string for which you want to count the characters.$mode
(optional): The mode of operation for the function. It can take one of the following values:0
(default): Returns an array where the keys are ASCII values of characters and the values are their frequencies.1
: Returns a string containing all unique characters that occur in the input string.2
: Returns a string containing all characters that do not occur in the input string.
Here’s an example usage of the count_chars()
function:
$input_string = "Hello, World!";
// Count the character frequencies
$char_frequencies = count_chars($input_string, 0);
// Print the result
foreach ($char_frequencies as $ascii => $frequency) {
$character = chr($ascii);
echo "Character: $character, Frequency: $frequency\n";
}
Output:
Character: !, Frequency: 1
Character: , Frequency: 1
Character: ,, Frequency: 1
Character: H, Frequency: 1
Character: W, Frequency: 1
Character: d, Frequency: 1
Character: e, Frequency: 1
Character: l, Frequency: 3
Character: o, Frequency: 2
Character: r, Frequency: 1
In this example, the count_chars()
function is used to count the frequencies of characters in the input string “Hello, World!”. The resulting array $char_frequencies
contains the frequencies of each character. The foreach
loop is then used to iterate over the array and print the character along with its frequency.
Note that you can also use the $mode
parameter to obtain different results, such as getting a string of unique characters or a string of characters that do not occur in the input string, depending on your requirements.