PHP or amazing behavior

I have unexpected results using OR as a logical OR in php.
Given the following code:

$a = false; $b = false; $c = true; # Test 1, using OR and assigning to a variable $value = $a OR $b OR $c; var_dump( $value ); # return bool(false) but why? # Test 2, using OR directly in var_dump var_dump( $a OR $b OR $c ); # return bool(true) as expected # Test 3, using || and assigning to a variable $value = $a || $b || $c; var_dump( $value ); # return bool(true) as expected # Test 4, using || directly in var_dump var_dump( $a || $b || $c ); # return bool(true) as expected 

Why do Test 1 and Test 2 give different results, even if they perform the same logical operation?

+5
source share
2 answers

Operator || and the OR operator does not behave the same. They cannot be used interchangeably.

If you want behavior || use it. Do not use OR unless you are in a situation where || will do the wrong thing.

For your situation, these two lines of code will behave exactly the same:

 $value = $a OR $b OR $c; ($value = $a) OR $b OR $c; 

In other words, your code is mostly fair:

 $value = $a; 

If you used the || operator , then these two are identical, as if you had such braces:

 $value = $a || $b || $c; $value = ($a || $b || $c); 

More details: http://php.net/manual/en/language.operators.precedence.php

+4
source

If you complete test 1 in parentheses, it will behave as expected:

 $value = ($a OR $b OR $c); 

When you run var_dump in test 2, you get the expected result, because var_dump completes the operation in parentheses.

It is usually recommended to wrap the operation in parentheses like this, especially with variable assignment.

In addition, the keywords "OR" and "||" don't behave the same way. See the documentation here: http://php.net/manual/en/language.operators.logical.php

0
source

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


All Articles