Lets say I want to sort some items and need to sort them by priority from highest to lowest (5,3,2,1). So highest priority 5 will end up being stored in $items[0] after the sort. Lets say there’s this code already in place to sort it:
$items = $items->sort(function(Item $a, Item $b)
{
if ($a->priority == $b->priority)
{
return 0;
}
return ($a->priority < $b->priority) ? 1 : -1;
});
Which somehow works, but I don’t know why it works.
I’m assuming return 0 keeps the compared item in its place. What does return 1 do? Does it move $a up the sorted array closer to array[0]? And return -1 moves $a down the array closer to array[10]?
Or does it actually move the $b variable?
SOLVED
Ok I cracked it with a bit of help from Pauly and phpdev. It actually moves the $b variable, not the $a variable inside the callback function. So I needed to alter the logic so it makes sense. -1 moves $b down the array, 1 moves $b up the array and 0 keeps $b in the same place.
$priorities = array(5, 8, 3, 10, 4, 3, 7);
usort($priorities, function($a, $b)
{
if ($a == $b)
{
// Same priority, keep same
echo "$a is same as $b, keeping the same\n";
return 0;
}
else if ($a > $b)
{
// $a is higher priority, move $b down array
echo "$a greater than $b, moving $b down array\n";
return -1;
}
else {
// $a is lower priority, move $b up array
echo "$b greater than $a, moving $b up array\n";
return 1;
}
});
var_dump($priorities);
This outputs:
10 greater than 8, moving 8 down array
10 greater than 7, moving 10 up array
10 greater than 3, moving 10 up array
10 greater than 4, moving 10 up array
10 greater than 5, moving 10 up array
10 greater than 3, moving 10 up array
10 greater than 8, moving 10 up array
5 greater than 3, moving 3 down array
7 greater than 5, moving 5 down array
8 greater than 5, moving 8 up array
5 greater than 4, moving 4 down array
5 greater than 3, moving 5 up array
5 greater than 4, moving 5 up array
8 greater than 7, moving 8 up array
4 greater than 3, moving 4 up array
3 is same as 3, keeping the same
4 greater than 3, moving 3 down array
array(7) {
[0]=> int(10)
[1]=> int(8)
[2]=> int(7)
[3]=> int(5)
[4]=> int(4)
[5]=> int(3)
[6]=> int(3)
}
-1 moves it down, 0 leaves it, 1 pushes it up.
http://www.php.net/manual/en/function.usort.php