5

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?

Eric
  • 2,784
  • 1
  • 20
  • 25

2 Answers2

4

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

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
  • Totally, I would hate to live in a world where `OR` and `||` are the same thing – Alec Teal Jan 11 '15 at 03:08
  • 1
    This answer need the link: http://php.net/manual/en/language.operators.precedence.php – sectus Jan 11 '15 at 03:21
  • 1
    Indeed it makes sense if OR has a lower precedence than =. Having logical operators with a lower precedence than an assignment operator feels a little unnatural though. Thanks for the detailed answer! – Eric Jan 11 '15 at 03:40
0

If you wrap test 1 in parenthesis, it will behave as expected:

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

When you run var_dump on test 2, you get the expected result because var_dump is wrapping the operation in parenthesis.

It is usually a good idea to wrap an operation in parenthesis like this, especially with variable assignment.

Also, the "OR" keyword and "||" do not behave the same way. See documentation here: http://php.net/manual/en/language.operators.logical.php

Seth
  • 1,353
  • 1
  • 8
  • 17