PHP
Count Frequency of All Values in an Indexed PHP Array
Determine the occurrences of each unique value within a PHP array by generating an associative array mapping values to their respective counts.
<?php
$data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape'];
$valueCounts = array_count_values($data);
/*
$valueCounts will be:
[
'apple' => 3,
'banana' => 2,
'orange' => 1,
'grape' => 1
]
*/
$numericData = [1, 2, 1, 3, 2, 1, 4];
$numericValueCounts = array_count_values($numericData);
// $numericValueCounts will be [1 => 3, 2 => 2, 3 => 1, 4 => 1]
?>
How it works: The `array_count_values` function takes an indexed array and returns an associative array. The keys of the new array are the unique values from the original array, and the values are their respective counts. This provides a quick and efficient way to get the frequency distribution of elements within the array.