Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OR surprising behavior [duplicate]

Tags:

php

I have some surprising results using OR as a logical OR in php.
Considering 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 Test 1 and Test 2 give different results even though they do the same logical operation?

like image 565
Eric Avatar asked Sep 30 '22 00:09

Eric


1 Answers

The || operator and OR operator do not behave the same. They cannot be used interchangably.

If you want || behaviour, then use it. Do not use OR unless you're in a situation where || would do the wrong thing.

As 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 basically just:

$value = $a;

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

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

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

like image 159
Abhi Beckert Avatar answered Oct 03 '22 03:10

Abhi Beckert