Sometimes you need to sort an associative array in more than one way. Let’s say you have an array such as this one, representing the toys inside a toy box. The keys are the name of the toy and the values are how many of each we have:

$items = array( "balls" => 5, "toy cars" => 1, "ropes" => 5, "dolls" => 3, "jumping jacks" => 5, "tea sets" => 2 );

And you need to sort this array in order to print a list displaying the toys of which we have the most showing up first. Those toys of which we have the same number (like balls and jumping jacks) should display in alphabetical ascending order. In this example, such a list would look like this:

5 balls

5 jumping jacks

5 ropes

3 dolls

2 tea sets

1 toy cars

I found an easy way to sort this array in php with the array_multisort function:

array_multisort(array_values($items),SORT_NUMERIC, SORT_DESC, array_keys($items),SORT_STRING, SORT_ASC, $items);

Just a quick and easy way to apply more than one sorting rule to an array.

Once you have the array sorted the right way, you can easily print the list:

foreach($items as $ikey => $value){ echo $value. " ". $ikey; }