PHP 7.x 後有新增一個比較的語法,可以依照比對 >、=、< 分別回傳 1、0、-1
PHP7 <=> Spaceship 運算子的語法
PHP7 之後,有新增 Spaceship operator 的操作語法:
- echo 2 <=> 1; // 1
- echo 2 <=> 2; // 0
- echo 2 <=> 3; // -1
- 更大數值也是一樣
- echo 2 <=> -1; // 1
- echo 2 <=> 4; // -1
- 用 if 來舉例
- if ($a == $b) = 0
- if ($a > $b) = 1
- if ($a < $b) = -1
下述摘錄自此篇:PHP: Comparison Operators - Manual
<?php // Integers echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // Floats echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // Strings echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 echo "a" <=> "aa"; // -1 echo "zz" <=> "aa"; // 1 // Arrays echo [] <=> []; // 0 echo [1, 2, 3] <=> [1, 2, 3]; // 0 echo [1, 2, 3] <=> []; // 1 echo [1, 2, 3] <=> [1, 2, 1]; // 1 echo [1, 2, 3] <=> [1, 2, 4]; // -1 // 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 // not only values are compared; keys must match $a = (object) ["a" => "b"]; $b = (object) ["b" => "b"]; echo $a <=> $b; // 1 ?>