Siteturbo
Siteturbo

Reputation: 11

PHP multiple OR logical operators in one IF statement

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.

Upvotes: 1

Views: 626

Answers (1)

homer
homer

Reputation: 902

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.

Upvotes: 2

Related Questions