RGS2014
RGS2014

Reputation: 71

How do I sort a PHP associative array first by value, then by key?

I have an associative array in which the keys are strings and the values are integers. I'm wanting to first of all sort the array by the values and then sort elements with the same value by their keys. I've managed to sort the array by the values using asort() but haven't worked out how to then sort by the keys.

Any Help?

Thanks

Upvotes: 2

Views: 91

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

uksort(
    $myArray,
    function ($a, $b) use ($myArray) {
        if ($myArray[$a] == $myArray[$b]) {
            return strcmp($a, $b);
        }
        return ($myArray[$a] < $myArray[$b]) ? -1 : 1;
   }
);

Upvotes: 2

Related Questions