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.
var_dump(1 || 2)to see what you're actually comparing with.==) vs strict comparisons (===). When you do$x == (1 || 2)it's actually being converted to$x == truebecause1 || 2is 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 === truewhich isn't true, because$xis an int. See php.net/manual/en/types.comparisons.php for more info.$x = 3;