Home  >  Article  >  php教程  >  PHP中逻辑运算符and/or与||/&&的一个坑

PHP中逻辑运算符and/or与||/&&的一个坑

WBOY
WBOYOriginal
2016-06-06 20:12:361331browse

我原来以为PHP中的 and 和 是一样的, 只是写法上为了可读性和美观, 事实上我错了. 这里面深藏了一个坑! 看以下代码: $bA = true;$bB = false;$b1 = $bA and $bB;$b2 = $bA $bB;var_dump($b1); // $b1 = truevar_dump($b2); // $b2 = false$bA = false;$bB =

美国加州的炉口坑

我原来以为PHP中的and&&是一样的, 只是写法上为了可读性和美观, 事实上我错了. 这里面深藏了一个坑!

看以下代码:

$bA = true;
$bB = false;
$b1 = $bA and $bB;
$b2 = $bA && $bB;
var_dump($b1); // $b1 = true
var_dump($b2); // $b2 = false
$bA = false;
$bB = true;
$b3 = $bA or $bB;
$b4 = $bA || $bB;
var_dump($b3); // $b3 = false
var_dump($b4); // $b4 = true

奇怪吧, and/&&or/||出来的结果竟然不一样的. 问题出在哪里呢?

我们再看一段代码!

$bA = true;
$bB = false;
var_dump($bA and $bB); // false
var_dump($bA && $bB); // false
$bA = false;
$bB = true;
var_dump($bA or $bB); // true
var_dump($bA || $bB); // true

更奇怪, 这时怎么是对的. 所以问题可能出现在=上, 一番google和文档,终于找到了答案!

运算符优先级

运算符优先级

通过这个表, 我们可以看到 and/&&or/|| 这两组运算符的优先级竟然是不一样的. andor的优先级是低于=的, 所以上面的代码就好理解了, 就是先做赋值然后再做了一个andor的逻辑运算, 这个运算的结果并没有存下来. 所以最后出来让我们匪夷所思的结果.

The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping.

下表列出了运算的优先级顺序, 越靠上的越高, 同一行的优先级相同. 相同优级的使用结合性进行分组处理.

结合性 运算符 额外信息
无结合性 clone new 克隆和new
[ 数组
** 算术
++ — ~ (int) (float) (string) (array) (object) (bool) @ 类型和自增/自减
无结合性 instanceof 类型
! 逻辑运算
* / % 算术
+ – . 算术和字符串
> 按位运算
无结合性 >= 比较运算
无结合性 == != === !== 比较运算
& 按位运算和引用
^ 按位运算
| 按位运算
&& 逻辑运算
| | 逻辑运算
?: 三元条件选择
= += -= *= /= .= %= &= = ^= >= => | 赋值
and 逻辑运算
xor 逻辑运算
or 逻辑运算
, 很多使用

总结

慎重使用and, orxor的逻辑运算符, 避免和赋值号以及&&||一起用, 以免发生不必要的逻辑错误.

( 完 )

版权所有:老白经 转载请保留来源信息。 >

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn