mythical_man_moth mythical_man_moth - 3 months ago 11
PHP Question

php logical operator comparison evaluation

here is what i'm trying to achieve:


if $x is either of these 3 values: 100, 200 or 300 - do something


I'm doing this:

if($x==("100"||"200"||"300"))
{
//do something
}


but
//do something
is executed even if
$x
is
400


I noticed that this works:

if($x=="100"||$x=="200"||$x=="300")
{
//do something
}


How is the first block of code different from the second block of code? What am I doing wrong?

Answer

The reason why your code isn't working is because the result of the expression:

('100' || '200' || '300') 

is always TRUE because the expression contains at least one truthy value.

So, the RHS of the expression is TRUE, while the LHS is a truthy value, therefore the entire expression evaluates to TRUE. The reason why this is happening is because of the == operator, which does loose comparison. If you used ===, the resulting expression would always be FALSE. (unless of course the value of $x is false-y.)

Let's analyze this:

Assuming $x equal '400':

  ($x == ('100'||'200'||'300'))

//  ^            ^
// true         true

Make sense now?

Bottom line here is: This is the wrong way of comparing 3 values against a common variable.

My suggestion is that you use in_array:

if(in_array($x, array('100', '200', '300')) {
   //do something...
}