5

I need to sort an array by values, but if values of elements are equal, I need to compare their keys and sort by them.

uasort($pages_arr, function($a, $b){
                if ($a == $b){
                   return ($key_a < $key_b) ? -1 : 1; 
                }
                return ($a < $b) ? -1 : 1;
            });

I dont understand, how can I get $key_a and $key_b values (keys of elements $a and $b). Values can be the same, keys aren't; How to resolve this problem?

1 Answer 1

6

Try the following, which uses the uksort function:

uksort($pages_arr, function($key_a, $key_b) use ($pages_arr) {
    $a = $pages_arr[$key_a];
    $b = $pages_arr[$key_b];
    if ($a == $b) {
       return ($key_a < $key_b) ? -1 : 1; 
    }
    return ($a < $b) ? -1 : 1;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.