anejoblanco
anejoblanco

Reputation: 13

Finding common values in array

I was wondering how I would go about displaying the most common values in an array, so far my script gives the single most common value but what if I wanted the 5 most common?

function array_most_common($array) {
   $counted = array_count_values($array); 
   arsort($counted); 
   return(key($counted));       
}

echo array_most_common($array);

Many thanks.

Upvotes: 1

Views: 741

Answers (1)

Jason McCreary
Jason McCreary

Reputation: 73021

Seems like you have it. I'd simply modify your function to return the the whole array so you can perform whatever logic you want afterwards:

function array_most_common($array) {
  return arsort(array_count_values($array));
}

Upvotes: 2

Related Questions