Skip to content
PHP Logo

What PHP function can be used to count the occurrences of each character in a string?

To count the occurrences of each character in a string in PHP, you can use the `count_chars()` function. This function returns an array with the ASCII value of the character as keys and the frequency of each character as values. By using this function, you can easily determine how many times each character appears in the given string.

php
$string = "hello world";
$charCounts = count_chars($string, 1);

foreach ($charCounts as $asciiValue => $count) {
    $character = chr($asciiValue);
    echo "Character '$character' appears $count times." . PHP_EOL;
}