Mike Barwick Mike Barwick - 2 years ago 80
PHP Question

PHP - if single value equals multiple options

So I understand this - and comparing/checking values. However, I was messing about and noticed the outcome for all my tests were the same - some of which I was taught (a) didn't work or (b) was incorrect.

Note, I'm running PHP7. Okay, to my point. I was able to achieve the same outcome checking if a single value equals one of multiple options...

These work...why? Def not the way I learned.

if ($status == 'in-progress' || 'in-review')
// and even
if ($status == ('in-progress' || 'in-review')) // kind of similar to ASP.NET Razor

I normally would repeat the check, like so:
if($stat == 'a' || $stat == 'b')
or even
which is essentially the same thing.

Is the first examples, correct? If not, why is it working? Or is this something frowned upon and not practiced - or maybe even something new?

Answer Source

First off to make it clear == has a higher precedence than ||. This means your two if statements look like this:

if (($status == 'in-progress') || 'in-review')
if ($status == ('in-progress' || 'in-review'))

Now for your first if statement regardless what value $status has and what the outcome of ($status == 'in-progress') is, since you have an OR in it and after it 'in-review' your if statement will always be true, since a non empty string is a truthy value.

For your second statement, this part ('in-progress' || 'in-review') comes literally down to TRUE || TRUE, which evaluates to TRUE. Now $status just needs to hold a truthy value and the if statement will be true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download