PHP
Counting Occurrences of All Unique Values in an Array
Learn how to quickly count how many times each unique value appears in a PHP array using the built-in `array_count_values` function, returning an associative array of counts.
<?php
$fruits = ['apple', 'banana', 'orange', 'apple', 'grape', 'banana', 'apple'];
// Count the occurrences of each fruit
$fruitCounts = array_count_values($fruits);
echo "Counts of each fruit:
";
print_r($fruitCounts);
/*
Output:
Array
(
[apple] => 3
[banana] => 2
[orange] => 1
[grape] => 1
)
*/
echo "
";
$numbers = [1, 5, 2, 1, 5, 1, 9, 2];
$numberCounts = array_count_values($numbers);
echo "Counts of each number:
";
print_r($numberCounts);
/*
Output:
Array
(
[1] => 3
[5] => 2
[2] => 2
[9] => 1
)
*/
How it works: The `array_count_values()` function is a simple yet powerful tool for analyzing the frequency of elements within an array. It processes an input array and returns an associative array where the keys are the unique values from the original array, and the corresponding values are their respective counts. This is useful for statistical analysis, identifying popular items, or validating data integrity.