Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering PHP arrays based on duplicate values

I have an array which contains duplicate values. I want to sort the array so that the values with the most duplicates appear first in line. Here's an example of my array:

array(1, 2, 3, 2, 1, 2, 2);

I want to sort this array so that it orders itself based on the amount of duplicates into the following:

array(2, 1, 3);

'2' has the most duplicates so it's sorted first, followed by values will less duplicates. Does anyone know how I can accomplish this?

like image 436
hohner Avatar asked Aug 17 '11 10:08

hohner


People also ask

Does PHP array keep order?

PHP array is an ordered map, so, it's a map that keeps the order. array elements just keep the order since they were added that's all.

Are PHP arrays ordered?

An array in PHP is actually an ordered map. So yes, they are always ordered.


1 Answers

 $acv=array_count_values($array); //  1=>2, 2=>3,3=>1
 arsort($acv); //save keys,           2=>3, 1=>2, 3=>1 
 $result=array_keys($acv); //get only keys   2,1,3
like image 121
RiaD Avatar answered Oct 13 '22 00:10

RiaD