mythical_man_moth
mythical_man_moth

Reputation: 249

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?

Upvotes: 0

Views: 379

Answers (2)

Karthik
Karthik

Reputation: 1488

you can take all values in array it is working Perfectly.

$x=400;

if(in_array($x, array('100', '200', '300'))) {
    echo $x.'is in array';
} else {
    echo $x.'is not in array';
}

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163228

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...
}

Upvotes: 3

Related Questions