[英]php why does or operator return 0 as true
In the following code: 在以下代码中:
$a = 0 or 1;
$b = 0 || 1;
echo "$a, $b"; // 0, 1
Why does $a
equal zero, I thought or
and ||
为什么
$a
等于零,我想or
和||
were interchangeable in PHP? 在PHP中是可以互换的吗? What exactly is going on with the
or
statement to make it return 0
? 是什么让
or
语句返回0
?
I would have assume both results would have been 1
making it echo 1, 1
. 我会假设两个结果都是
1
,使它回显1, 1
。
or
is lower precedence than =
which is lower precedence than ""
or
优先级低于=
优先级低于""
So your code is equivalent to: 所以你的代码相当于:
($a = 0) or 1;
$b = (0 || 1);
See the precedence table in the PHP manual. 请参阅PHP手册中的优先级表 。
It's because of the rules of precedence in PHP. 这是因为PHP中的优先规则。 The assignment
=
operator has a lower precedence than the logical ||
赋值
=
运算符的优先级低于逻辑||
operator, but a higher precedence than the logical OR
operator. 运算符,但优先级高于逻辑
OR
运算符。 See here: http://php.net/manual/en/language.operators.precedence.php 请参见此处: http : //php.net/manual/en/language.operators.precedence.php
Its because of the order of precedence 这是因为优先顺序
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
http://php.net/manual/en/language.operators.logical.php http://php.net/manual/en/language.operators.logical.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.