PHP 操作符

逻辑运算符用于组合两个或多个条件。 PHP 有以下逻辑运算符:

  • && - 逻辑 AND 运算符
  • and - 逻辑 AND 运算符
  • || - 逻辑 OR 运算符
  • - 逻辑或运算符
  • ! - 逻辑非运算符
  • 异或 - 逻辑异或运算符

逻辑与运算符(&& / and)

逻辑与运算符用于组合两个或多个条件,只有当所有条件都满足时才返回 true为 true,否则返回 false。请考虑下面的示例来理解这个概念:

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

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

上述代码的输出将是:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25]. 

逻辑 OR 运算符(|| / or)

逻辑或运算符用于组合两个或多个条件,当任何一个条件为 true 时返回 true,否则返回 false。考虑以下示例:

<?php
function range_func($x){
  //|| (or) 运算符用于组合条件
  //当 x < 100 或 x > 200 时返回 true
  if($x < 100 or $x > 200)
    echo "$x do not belongs to range [100, 200].\n";   
  else
    echo "$x belongs to range [100, 200].\n"; 
}

range_func(50);
range_func(100);
range_func(150);
?> 

上述代码的输出将是:

50 do not belongs to range [100, 200].
100 belongs to range [100, 200].
150 belongs to range [100, 200]. 

逻辑 NOT 运算符 (!)

逻辑 NOT 运算符用于返回相反的布尔结果。考虑下面的示例:

<?php
function range_func($x){
  //!运算符用于返回
  //当 x <= 100 时为真
  if(!($x >= 100))
    echo "$x is less than 100.\n";   
  else
    echo "$x is greater than or equal to 100.\n"; 
}

range_func(50);
range_func(100);
range_func(150);
?> 

上述代码的输出将是:

50 is less than 100.
100 is greater than or equal to 100.
150 is greater than or equal to 100. 

逻辑 XOR 运算符 (xor)

逻辑 XOR 运算符在以下情况下返回 true:任何条件为 true,但不能同时为 true,否则返回 false。考虑以下示例:

<?php
function range_func($x){
  //异或运算符在任一情况下返回 true
  //x >= 100 或 x <= 200;返回假
  //当两个条件都为真或没有一个条件为真时
  if($x >= 100 xor $x <= 200)
    echo "$x do not belongs to range [100, 200].\n";   
  else
    echo "$x belongs to range [100, 200].\n"; 
}

range_func(50);
range_func(100);
range_func(150);
?> 

上述代码的输出将是:

50 do not belongs to range [100, 200].
100 belongs to range [100, 200].
150 belongs to range [100, 200].