PHP
Count Value Occurrences in an Array
Learn to quickly count how many times each unique value appears in a PHP array, generating an associative array of counts with array_count_values.
$fruits = ['apple', 'banana', 'orange', 'apple', 'grape', 'banana', 'apple'];
$counts = array_count_values($fruits);
print_r($counts);
// Output: Array
// (
// [apple] => 3
// [banana] => 2
// [orange] => 1
// [grape] => 1
// )
How it works: The `array_count_values()` function counts all the values in an array and returns an associative array. The keys of the returned array are the unique values from the input array, and their corresponding values are the number of times each value appears. This is excellent for frequency analysis, generating statistics, or categorizing data based on item counts.