J V
J V

Reputation: 11936

If uasort callback returns 0, elements are reversed

If I usort an array and the callback returns 0, the elements are reversed.

<?php

$a = array("1", "2", "3");

print_r($a);

function nosort($a, $b){
    return 0;
}

uasort($a, "nosort");

print_r($a);

Results in:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Array
(
    [2] => 3
    [1] => 2
    [0] => 1
)

Why does this happen? Wouldn't 0 not switching elements be a more sane default?

Upvotes: 2

Views: 355

Answers (2)

Mr. Llama
Mr. Llama

Reputation: 20909

From the documentation of uasort:

Note
If two members compare as equal, their relative order in the sorted array is undefined.

You've defined all entries in the array as having equal comparisons so PHP can do whatever it feels like with them. The fact that it came out in reverse order may just be coincidence.
You should not, under any circumstances, depend on this behavior as it is undefined.

Upvotes: 2

Paul Roub
Paul Roub

Reputation: 36448

uasort() is not a stable sort - that is, there's no guarantee that two equal elements (those for which the comparison returns 0) will retain their order. They may, they may not. The fact that they happen to be reversed here isn't something you should count on, either.

The uasort() docs include an example of a stable variation on uasort(), if you need that.

Upvotes: 1

Related Questions