Reputation: 8992
I have this code:
$ids = array(13952979,13952983,13952997,13952999,13953001,13953009,13953011,13953013);
uasort($ids, function($a, $b){
echo $a . ',' . $b . "<br>";
});
This ends up echoing:
13952999,13952983
13953013,13952999
13952999,13952997
13953011,13952999
13952999,13952979
13953009,13952999
13953001,13952999
13952997,13952979
13952983,13952997
13953013,13953001
13953009,13953013
13953011,13953013
13953009,13953011
Notice that the combination 13952979,13952983
- or its reverse - is not one of the comparisons. This causes the sort to only sort partially.
Why is it not performing a comparison between 13952979
and 13952983
? How can I make it so that it performs all possible comparisons?
Upvotes: 1
Views: 48
Reputation: 32860
You are not sorting, at least not with the current code. There is no comparison done in you function, thus PHP
uses the default return value, which is equal to 0 (all items are equal), resulting in the incorrect behaviour you noticed.
This should behave better:
uasort($ids, function($a, $b){
echo $a . ',' . $b . "<br>";
return $a - $b; // or $b - $a, depending on the sort order you need
});
Upvotes: 0
Reputation: 781779
It's not necessary to perform all possible comparisons to sort an array. It performed the comparisons 13952997,13952979
and 13952983,13952997
. From these, it can infer the result of 13952979,13952983
, so it doesn't need to do it explicitly.
Upvotes: 2