Skip to main content

PHP – multi-sort of associative array in PHP

This is a complete multi-sort example of associative array in PHP. We have first sorted an associative array by values in descending order then sorted an associative array by keys in ascending order.

  1. <?php
  2. $asso_arr = Array
  3. (
  4. ‘banana’ => 2,
  5. ‘cherry’ => 1,
  6. ‘orange’ => 3,
  7. ‘grapefruit’ => 1,
  8. ‘apple’ => 1
  9. );
  10. $values = array_values($asso_arr);
  11. $keys = array_keys($asso_arr);
  12. //first sort by values desc, then sort by keys asc
  13. array_multisort($values, SORT_DESC, $keys, SORT_ASC, $asso_arr);
  14. print_r($asso_arr);
  15. ?>

 

Output:

Array
(
[orange] => 3
[banana] => 2
[apple] => 1
[cherry] => 1
[grapefruit] => 1
)

PHPZAG.COM is a popular PHP tutorial blog that publishes useful tips and tutorials for PHP programmer. If you would like to be kept up to date with our posts, you can subscribe to our RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera