“和&”操作员工作正常,但“OR |”并且“或者”或“^”始终为真

时间:2013-06-28 11:59:10

标签: php operators

我使用逻辑运算符来测试变量,但 AND& 运算符正常工作但 OR | 和Either-OR ^ 始终为true。
为什么呢?

$a = 6;
$b = 6;

if ($a OR $b == 3) {
    echo 'true <br />';
}
else {
    echo 'false <br />';
}

4 个答案:

答案 0 :(得分:3)

问题在于您的语法。

您需要单独查看表达式。

if($a) OR if($b == 3)

就是你在做什么。

你想要的是:

if($a == 3 || $b == 3)

如果您单独查看$a,除了0之外的任何值都会返回true,因为true

而生成整个等式OR

答案 1 :(得分:2)

因为你必须对布尔结果进行OR处理 - 你读得太像英语了。

if ($a == 3 || $b == 3)

而不是

if ($a OR $b == 3)

答案 2 :(得分:2)

这是一个优先事项 - 请点击http://php.net/manual/en/language.operators.precedence.php了解更多详情。

其他答案都会为您提供所需的代码。

答案 3 :(得分:2)

$a = true
$b = true
if($a and $b)   TRUE if both $a and $b are TRUE.

参考:http://php.net/manual/en/language.operators.logical.php