PHP 操作符

下面的示例说明了 PHP 比较运算符的用法:==、!=、<>、===、!==、>、<、>=、<=、 <=>。

<?php
echo "10 == 10: ".(int)(10 == 10)."\n";
echo "10 != 10: ".(int)(10 != 10)."\n";
echo "10 === 10.0: ".(int)(10 === 10.0)."\n";
echo "10 !== 10.0: ".(int)(10 !== 10.0)."\n";
echo "10 <> 10: ".(int)(10 <> 10)."\n";
echo "10 < 20: ".(int)(10 < 20)."\n";
echo "10 > 20: ".(int)(10 > 20)."\n";
echo "10 <= 20: ".(int)(10 <= 20)."\n";
echo "10 >= 20: ".(int)(10 >= 20)."\n";

echo "\nSpaceship operator:\n";
echo "10 <=> 20: ".(int)(10 <=> 20)."\n";
echo "20 <=> 20: ".(int)(20 <=> 20)."\n";
echo "30 <=> 20: ".(int)(30 <=> 20)."\n";
?> 

上述代码的输出将是:

10 == 10: 1
10 != 10: 0
10 === 10.0: 0
10 !== 10.0: 1
10 <> 10: 0
10 < 20: 1 10 > 20: 0
10 = 20: 0

Spaceship operator:
10 <=> 20: -1
20 <=> 20: 0
30 <=> 20: 1 

这些比较运算符通常返回布尔结果,这非常有用,可以用来构造条件语句:如下例所示:

<?php
function range_func($x){
  //&&(与)运算符用于组合条件
  //仅当 x >= 10 且 x <= 25 时才返回 true
  if($x >= 10 and $x <= 25)
    echo "$x 属于范围 [10, 25].\n"; 
  else
    echo "$x 不属于范围 [10, 25].\n";
}

range_func(15);
range_func(25);
range_func(50);
?> 

上述代码的输出将是:

15 属于范围 [10, 25].
25 属于范围 [10, 25].
50 不属于范围 [10, 25].