PHP – multi-sort of associative array in PHP

Oct 08, 2013, by admin

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.

<?php
    $asso_arr = Array
    (
    ‘banana’ => 2,
    ‘cherry’ => 1,
    ‘orange’ => 3,
    ‘grapefruit’ => 1,
    ‘apple’ => 1
    );
    $values = array_values($asso_arr);
    $keys = array_keys($asso_arr);
    //first sort by values desc, then sort by keys asc
    array_multisort($values, SORT_DESC, $keys, SORT_ASC, $asso_arr);
    print_r($asso_arr);
    ?>

Output:

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

To get more updates like the Bugtreat Technologies and like the page cs cart templates to view our new templates