I am pretty new to PHP7 and so far it seems great and powerful. I have been using PHP5.6 so I started understanding the usage of spaceship operator <=>
. But somehow I couldn't get the logic that statement returns -1
. I know the point of returning to 0
or 1
which are false
or true
. Can anyone clarify the usage of return -1
?
Function normal_sort($a, $b) : int
{
if( $a == $b )
return 0;
if( $a < $b )
return -1;
return 1;
}
function space_sort($a, $b) : int
{
return $a <=> $b;
}
$normalArray = [1,34,56,67,98,45];
//Sort the array in asc
usort($normalArray, 'normal_sort');
foreach($normalArray as $k => $v)
{
echo $k.' => '.$v.'
';
}
$spaceArray = [1,34,56,67,98,45];
//Sort it by spaceship operator
usort($spaceArray, 'space_sort');
foreach($spaceArray as $key => $value)
{
echo $key.' => '.$value.'
';
}
Answer
You have three possibilities when comparing the two values that are passed to a comparison function: $a < $b
, $a == $b
, or $a > $b
. So you need three distinct return values and PHP has chosen the integers: -1
, 0
, and 1
. I guess it could just as easily be strings lesser
, equal
and greater
or integers 5
, 7
and 9
or any combination, but it's not.
From the manual usort()
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
$a < $b
return-1
$a == $b
return0
$a > $b
return1
This is NOT how types work in PHP, but you can think of it like this: is $a > $b
? where -1
means false
, 1
means true
and 0
means neither (equal).
No comments:
Post a Comment