phparrayssortingduplicatescustom-sort

Sort a flat array by number of occurences descending and remove duplicates


I have an automatically generated PHP array that looks something like:

[1] => item
[2] => bar
[3] => plusgallery
[4] => size
[5] => dynamic
[6] => size
[7] => dynamic
[8] => size
[9] => size

(it actually consists of around 3000 items, this is just a chunk)

I used array_count_values() on it, and it generated an array such as:

[item] => 1
[bar] => 1
[plusgallery] => 1
[size] => 4
[dynamic] => 2

How could I get it to sort into another array based on the value of the keys, highest to lowest? I'd expect it to look something like:

[1] => size
[2] => dynamic
[3] => item
[4] => bar
[5] => plusgallery

Solution

  • Use arsort in combination with array_keys:

    $countedArray = array_count_values($array);
    arsort( $countedArray )
    array_keys( $countedArray );
    

    Live Demo

    The result is:

    array(5) {
      [0]=>
      string(4) "size"
      [1]=>
      string(7) "dynamic"
      [2]=>
      string(11) "plusgallery"
      [3]=>
      string(3) "bar"
      [4]=>
      string(4) "item"
    }
    

    (The last three items are swapped but I think that shouldn't matter)