PHP
Count Occurrences of Values in a PHP Array
Discover how to efficiently count how many times each unique value appears within a PHP array, generating a frequency map or histogram of values.
<?php
$fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape'];
$counts = array_count_values($fruits);
print_r($counts);
// Output:
// Array
// (
// [apple] => 3
// [banana] => 2
// [orange] => 1
// [grape] => 1
// )
$numbers = [1, 5, 2, 1, 5, 10, 2, 1];
$number_counts = array_count_values($numbers);
print_r($number_counts);
// Output:
// Array
// (
// [1] => 3
// [5] => 2
// [2] => 2
// [10] => 1
// )
?>
How it works: The `array_count_values()` function counts all the values of an array and returns an associative array where the keys are the unique values from the input array, and the values are their respective frequencies (how many times they occurred). This is perfect for generating histograms, frequency maps, or quickly summarizing data distribution.