Something similar to this: Get the element with the 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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With