PHP7 (return -1) 中的飞船操作员混淆
Spaceship operator confusion in PHP7 (return -1)
我是 PHP7 的新手,到目前为止它看起来非常强大。我一直在使用 PHP5.6,所以我开始了解飞船运算符 <=>
的用法。但不知何故,我无法理解语句 returns -1
的逻辑。我知道返回 0
或 1
的意义,即 false
或 true
。任何人都可以澄清 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.'<br>';
}
$spaceArray = [1,34,56,67,98,45];
//Sort it by spaceship operator
usort($spaceArray, 'space_sort');
foreach($spaceArray as $key => $value)
{
echo $key.' => '.$value.'<br>';
}
比较传递给比较函数的两个值时,您有三种可能性:$a < $b
、$a == $b
或 $a > $b
。因此,您需要三个不同的 return 值,并且 PHP 选择了整数:-1
、0
和 1
。我想它可以很容易地是字符串 lesser
、equal
和 greater
或整数 5
、7
和 9
或任何组合,但是不是。
来自手册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
return 0
$a > $b
return 1
这不是类型在 PHP 中的工作方式,但您可以这样想:是 $a > $b
吗?其中 -1
表示 false
,1
表示 true
,0
表示两者都不(相等)。
我是 PHP7 的新手,到目前为止它看起来非常强大。我一直在使用 PHP5.6,所以我开始了解飞船运算符 <=>
的用法。但不知何故,我无法理解语句 returns -1
的逻辑。我知道返回 0
或 1
的意义,即 false
或 true
。任何人都可以澄清 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.'<br>';
}
$spaceArray = [1,34,56,67,98,45];
//Sort it by spaceship operator
usort($spaceArray, 'space_sort');
foreach($spaceArray as $key => $value)
{
echo $key.' => '.$value.'<br>';
}
比较传递给比较函数的两个值时,您有三种可能性:$a < $b
、$a == $b
或 $a > $b
。因此,您需要三个不同的 return 值,并且 PHP 选择了整数:-1
、0
和 1
。我想它可以很容易地是字符串 lesser
、equal
和 greater
或整数 5
、7
和 9
或任何组合,但是不是。
来自手册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
这不是类型在 PHP 中的工作方式,但您可以这样想:是 $a > $b
吗?其中 -1
表示 false
,1
表示 true
,0
表示两者都不(相等)。