PHP: Most frequent value in array

$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);
  • array_count_values() gets the count of the number of times each item appears in an array
  • arsort() sorts the array by number of occurrences in reverse order
  • array_keys() gets the actual value which is the array key in the results from array_count_values()
  • array_slice() gives us the first five elements of the results

Demo

$array = [1,2,3,4,238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);

array (
  0 => 238,
  1 => 55,
  2 => 7,
  3 => 4,
  4 => 3,
)

Leave a Comment