Something similar to this: http://stackoverflow.com/questions/1053843/get-element-with-highest-occurrence-in-an-array
Difference is I need more than 1 result, need 5 results altogether. So the 5 top highest occurence in a (large) array.
Thanks!
Something similar to this: http://stackoverflow.com/questions/1053843/get-element-with-highest-occurrence-in-an-array
Difference is I need more than 1 result, need 5 results altogether. So the 5 top highest occurence in a (large) array.
Thanks!
Build the array of counts and put them in reverse order:
$mode = array_count_values($input);
arsort($mode);
$i = 0;
foreach ($mode as $k => $v) {
$i++;
echo "$i. $k occurred $v times\n";
if ($i == 5) {
break;
}
}
PHP actually provides some handy array functions you can use to achieve this.
Example:
<?php
$arr = array(
'apple', 'apple', 'apple', 'apple', 'apple', 'apple',
'orange', 'orange', 'orange',
'banana', 'banana', 'banana', 'banana', 'banana',
'pear', 'pear', 'pear', 'pear', 'pear', 'pear', 'pear',
'grape', 'grape', 'grape', 'grape',
'melon', 'melon',
'etc'
);
$reduce = array_count_values($arr);
arsort($reduce);
var_dump(array_slice($reduce, 0, 5));
// Output:
array(5) {
["pear"]=> int(7)
["apple"]=> int(6)
["banana"]=> int(5)
["grape"]=> int(4)
["orange"]=> int(3)
}
EDIT: Added array_slice, as used in Alix's post below.
Here you go:
$yourArray = array(1, "hello", 1, "world", "hello", "world", "world");
$count = array_count_values($yourArray);
arsort($count);
$highest5 = array_slice($count, 0, 5);
echo '<pre>';
print_r($highest5);
echo '</pre>';