0

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?

2 Answers 2

3

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...
}
Sign up to request clarification or add additional context in comments.

3 Comments

i don't know who downvoted him but i guess it was because his initial response was something else. my earlier comment was directed to his initial response.
thank you for your response jacob - that explanation certainly helps a lot!
@Gunner: initial response was very far from answer. That' was completely a post instead of answer
0

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';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.