简体   繁体   中英

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 || were interchangeable in PHP? What exactly is going on with the or statement to make it return 0 ?

I would have assume both results would have been 1 making it echo 1, 1 .

or is lower precedence than = which is lower precedence than ""

So your code is equivalent to:

($a = 0) or 1;
$b = (0 || 1); 

See the precedence table in the PHP manual.

It's because of the rules of precedence in PHP. The assignment = operator has a lower precedence than the logical || operator, but a higher precedence than the logical OR operator. See here: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM