PHP
Count Value Occurrences in PHP Array
Learn to efficiently count the frequency of each unique value within a PHP array using `array_count_values()`, ideal for statistics and data analysis.
$items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape'];
// Count the occurrences of each value
$valueCounts = array_count_values($items);
print_r($valueCounts);
// Example with numeric values
$numbers = [1, 5, 2, 1, 5, 1, 3, 2];
$numberCounts = array_count_values($numbers);
print_r($numberCounts);
How it works: The `array_count_values()` function is used to count all the values in an array and return an associative array where the keys are the unique values from the original array, and the values are their respective frequencies. This is highly useful for basic statistical analysis, tallying items, or understanding data distribution within a collection.