3

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 in_array() 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?

PeeHaa
  • 66,697
  • 53
  • 182
  • 254
Mike Barwick
  • 6,069
  • 4
  • 48
  • 72
  • 4
    Read up on [type juggling](http://php.net/manual/en/language.types.type-juggling.php). 'in-review' is a not an empty string so it is TRUE. So your first if statement says if ($status == 'in-progress' || TRUE). The second says if ($status == (true || true)). Type juggling is important to understand in PHP? – John Conde Apr 20 '16 at 17:33

2 Answers2

6

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.

Rizier123
  • 56,111
  • 16
  • 85
  • 130
3

No, that code will never work. || has a lower precedence than ==, so you're comparing $status against the first value, then boolean || "or" the other value

if (($status == 'foo') || ('bar'))

You have to compare the values individually:

 if (($status == 'foo') || ($status == 'bar'))

And this gets tedious for many values. A quick hack is to use an array:

 if (in_array($status, array('foo', 'bar', 'baz', 'qux', 'etc...')))
Marc B
  • 340,537
  • 37
  • 382
  • 468