<?php
$intA = 1;
$intB = 2;
$intC = 1;
echo '整型比较:<br>';
echo $intA <=> $intC; // 返回 0
echo '<br>';
echo $intA <=> $intB; // 返回 -1
echo '<br>';
echo $intB <=> $intC; // 返回 1
<?php
echo '字符串比较:<br>';
echo 'PHP 7' <=> 'PHP 7'; //返回 0
echo '<br>';
echo 'a' <=> 'b'; // 返回 -1
echo '<br>';
echo 'z' <=> 'x'; // 返回 1
<?php
echo '数组比较:<br>';
echo [1,2,3] <=> [1,2,3]; // 0
echo "<br>";
echo [1,2,3] <=> [3,2,1]; // -1
echo "<br>";
echo [3,2,1] <=> [1,2,3]; // 1
<?php
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 0
<?php
// 老的 if 方式比较
function normal_sort($a, $b) : int
{
if($a == $b) {
return 0;
} elseif ($a < $b) {
return -1;
} else {
return 1;
}
}
// 新的太空飞船操作符比较
function space_sort($a, $b) : int
{
return $a <=> $b;
}
$normalArray = [1,34,56,67,98,45];
usort($normalArray, 'normal_sort');
foreach($normalArray as $k => $v) {
echo $k.' => '.$v.'<br>';
}
//SpaceShip example
$sarray = [1,34,56,67,98,45];
usort($sarray, 'space_sort');
foreach($sarray as $key => $value) {
echo $key.' => '.$value.'<br>';
}
0 => 1
1 => 34
2 => 45
3 => 56
4 => 67
5 => 98
0 => 1
1 => 34
2 => 45
3 => 56
4 => 67
5 => 98