X

PHP7 Spaceship 運算子的語法

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

&lt;?php
// Integers
echo 1 &lt;=&gt; 1; // 0
echo 1 &lt;=&gt; 2; // -1
echo 2 &lt;=&gt; 1; // 1

// Floats
echo 1.5 &lt;=&gt; 1.5; // 0
echo 1.5 &lt;=&gt; 2.5; // -1
echo 2.5 &lt;=&gt; 1.5; // 1

// Strings
echo "a" &lt;=&gt; "a"; // 0
echo "a" &lt;=&gt; "b"; // -1
echo "b" &lt;=&gt; "a"; // 1
echo "a" &lt;=&gt; "aa"; // -1
echo "zz" &lt;=&gt; "aa"; // 1

// Arrays
echo [] &lt;=&gt; []; // 0
echo [1, 2, 3] &lt;=&gt; [1, 2, 3]; // 0
echo [1, 2, 3] &lt;=&gt; []; // 1
echo [1, 2, 3] &lt;=&gt; [1, 2, 1]; // 1
echo [1, 2, 3] &lt;=&gt; [1, 2, 4]; // -1

// Objects
$a = (object) ["a" =&gt; "b"];
$b = (object) ["a" =&gt; "b"];
echo $a &lt;=&gt; $b; // 0

$a = (object) ["a" =&gt; "b"];
$b = (object) ["a" =&gt; "c"];
echo $a &lt;=&gt; $b; // -1

$a = (object) ["a" =&gt; "c"];
$b = (object) ["a" =&gt; "b"];
echo $a &lt;=&gt; $b; // 1

// not only values are compared; keys must match
$a = (object) ["a" =&gt; "b"];
$b = (object) ["b" =&gt; "b"];
echo $a &lt;=&gt; $b; // 1
?&gt;
Tsung: 對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.
Related Post