PHP xor returns wrong value

允我心安 提交于 2020-02-15 07:33:08

问题


Using php 7.1.0 I'm running this little test:

<?php

$a = true;
$b = true;

$value = $a xor $b;
if ($value == true) {
    print "bad!\n";
} else {
    print "good\n";
}    

and it's coming back and saying bad. Why? An xor of two true values should be FALSE, not true.


回答1:


The problem is operator precedence. The xor operator has lower precedence than =, so your statement is equivalent to:

($value = $a) xor $b;

You need to write:

$value = ($a xor $b);

or

$value = $a ^ $b;

The ^ operator is bit-wise XOR, not boolean. But true and false will be converted to 1 and 0, and the bit-wise results will be equivalent to the boolean results. But this won't work if the original values of the variables could be numbers -- all non-zero numbers are truthy, but when you perform bit-wise XOR with them you'll get a truthy result for any two numbers that are different.

See the PHP Operator Precedence Table

See the related Assignment in PHP with bool expression: strange behaviour



来源:https://stackoverflow.com/questions/41799954/php-xor-returns-wrong-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!