Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get element with 5 highest occurrence in an array

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!

like image 531
Patrick Avatar asked Feb 01 '10 12:02

Patrick


1 Answers

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.

like image 81
Matt Avatar answered Oct 05 '22 21:10

Matt