Php why operator or operator return 0 as true

In the following code:

$a = 0 or 1; $b = 0 || 1; echo "$a, $b"; // 0, 1 

Why $a is zero, I thought that or and || are interchangeable in PHP? What exactly happens with the or operator to return it 0 ?

I would suggest that both results would be 1 , making it echo 1, 1 .

+5
source share
3 answers

or has a lower priority than = , which has a lower priority than ""

So your code is equivalent:

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

See the priority table in the PHP manual.

+8
source

This is due to priority rules in PHP. Assignment operator = has a lower priority than the logical operator || , but higher priority than the logical operator OR . See here: http://php.net/manual/en/language.operators.precedence.php

0
source

Due to priority order

 // 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

0
source

Source: https://habr.com/ru/post/1205310/


All Articles