1

I have a question about IF statements with multiple logical OR operators.

If we let:

$x=1;

A. I typical would write a IF statement comparing two items like this:

if($x == 1 || $x == 2) echo 'good';
else echo 'bad';

B. But, is this a valid IF statement? If not, why? (because it seems to work)

if($x == (1 || 2)) echo 'good';
else echo 'bad';

C. I typical would write a third comparison like this:

if($x == 1 || $x == 2 || $x == 3) echo 'good';
else echo 'bad';

D. What about this, following suit with B, above? (it does not seem to work)

if($x == (1 || 2 || 3)) echo 'good';
else echo 'bad';

The example in B, above works, but not the example in D. Why?

I cannot find any PHP documentation as to why.

11
  • 2
    Only A and C are correct. Commented Nov 17, 2021 at 21:50
  • 3
    Use var_dump(1 || 2) to see what you're actually comparing with. Commented Nov 17, 2021 at 21:50
  • 1
    You're running into issues with loose comparisons (==) vs strict comparisons (===). When you do $x == (1 || 2) it's actually being converted to $x == true because 1 || 2 is truthy. And $x = 1; is truthy, so it's acting like it works. (But $x = 3; is also truthy... so try that and see what happens). But if you were to do $x === (1 || 2) it would then compare $x === true which isn't true, because $x is an int. See php.net/manual/en/types.comparisons.php for more info. Commented Nov 17, 2021 at 21:54
  • 2
    Then try $x = 3; Commented Nov 17, 2021 at 21:54
  • 1
    So, I guess it was working by coincidence. Commented Nov 17, 2021 at 22:06

1 Answer 1

2

Here is what happens for every version:

A. $x == 1 || $x == 2

PHP will compare $x with the value 1, this is true so it can short-circuit the if and echo 'good'.

B. $x == (1 || 2)

PHP will evaluate 1 || 2 because parentheses indicate the priority, as the result should be a boolean expression it will cast 1 to a boolean which evaluates to true so the expression becomes $x == true.

Now PHP will evaluate this expression. First it will cast both types to the same, according to the documentation, it will "Convert both sides to bool". So, same as above, as $x is 1 it will be cast to true and then the expression becomes true == true which is true.

C. $x == 1 || $x == 2 || $x == 3

It is the same as A.

D. $x == (1 || 2 || 3)

It is quite the same as B.

And, for the record 1 == (1 || 2 || 3) evaluates to true.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.