PHP Assoc Array custom usort function

How can I sort the keys in descending order by their value and if two keys have the same quantity, I must print them in alphabetical order. I know that probably a user function must be created, but i was not able to learn how to make those.

Array:

array(3) {
  ["motes"]=>
  int(3)
  ["shards"]=>
  int(5)
  ["fragments"]=>
  int(5)
}

Output:

fragments: 5
shards: 5
motes: 3

1 answer

  • answered 2018-11-08 07:57 Nick

    You can use a user defined function with uksort to achieve what you want. By also passing the array to the function, we can cheat and sort on the values before sorting on the keys:

    $array = array('motes' => 3, 'shards' => 5, 'fragments' => 5);
    uksort($array, function ($a, $b) use ($array) { 
        if ($array[$a] < $array[$b]) return 1;
        elseif ($array[$a] > $array[$b]) return -1; 
        else return strcmp($a, $b); });
    print_r($array);
    

    Output

    Array ( 
        [fragments] => 5
        [shards] => 5
        [motes] => 3 
    )
    

    Demo on 3v4l.org