views:

85

answers:

3

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!

+1  A: 

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;
  }
}
cletus
Your badge count is so cool... 12, 2^7 - 1, 2^8 + 1!
Alix Axel
+8  A: 

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.

Matt
+6  A: 

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>';
Alix Axel
+1 for `array_slice`
Matt
@Matt: Thanks, when I posted my answer I didn't realize you were already using the `array_count_values()` function.
Alix Axel