strcmp()和太空船操作员(<;=>;)之间的区别是什么


What is the difference between strcmp() and Spaceship Operator (<=>)

PHP 7中,我们有一个新的操作员,宇宙飞船操作员<=>,我发现它与strcmp()非常相似(如果不相同的话)。

它们之间有什么区别吗?

编辑:我问他们两者之间的区别,而不是refered什么是<=>("太空船"操作员)在PHP 7中?或者什么是<=>("太空船"操作员)在PHP 7中?

strcmp-这是函数用于"二进制安全"字符串比较

如果左侧较小,则宇宙飞船操作符(<=>)返回-1;如果值相等,则返回0;如果左侧较大,则返回1。它可以用于所有具有与<lt;=,==,>=,>。此运算符的行为与strcmp()或version_compare()类似。此运算符可用于整数、浮点、字符串、数组、对象等。

例如,您可以比较数组对象,通过浮动可以得到不同的结果:

$var1 = 1.3;
$var2 = 3.2;
var_dump($var1 <=> $var2); // int(-1)
var_dump(strcmp($var1, $var2)); // int(-2)

以及其他差异。。。

更多示例此

根据官方文件:

"<=>"返回"一个小于、等于或大于零的整数",而"strcmp"返回"lt;0、=0或>0",因此您可能找不到任何差异。

通常情况下,这已经足够了,因为我们不在乎返回的确切值,但是,有一些东西显示如下:

echo 5<=>1、//1
echo strcmp(5,1);//4

我从宇宙飞船中永远无法得到1.0,-1以外的值。

  • <=>总是返回-1、0或1。另一方面,strcmp()通常返回小于-1或大于1的整数:第一个不同字符的字符代码差
  • <=>可以用于所有通用PHP值,而strcmp()仅比较字符串
  • 当两者都应用于字符串时,<=>strcmp()产生相同的符号,尽管不一定是相同的绝对值
  • 在不同类型上使用时,"与各种类型进行比较"规则适用于<=>,而strcmp()的自变量首先转换为string。这可能会导致明显不同的结果,如以下示例所示:
// Int 19 is converted to string '19', int 120 is converted to string '120',
// then only the first differing chars (the second ones) count.
echo strcmp(19, 120), "'n"; // == 7, as '9' is larger than '2'
// No conversion, numeric comparison.
echo 19 <=> 100, "'n'n";    // == -1
// Bool false is converted to string '', int 0 is converted to string '0'.
echo strcmp(false, 0), "'n"; // == -1
// Int 0 is converted to false.
echo false <=> 0, "'n'n";    // == 0
// Bool true is converted to string '1', which is "smaller" than letter 't'.
echo strcmp(true, 'true'), "'n"; // == ord('1') - ord('t') == -67
// String 'true' is converted to bool true, since it is not `empty()`.
echo true <=> 'true', "'n'n";    // == 0
// Int 1 is converted to string '1', which is greater then space (' ').
echo strcmp(1, ' 2'), "'n"; // == 17
// String ' 2' is converted to int 2.
echo 1 <=> ' 2', "'n'n";    // == -1