mythical_man_moth mythical_man_moth - 1 year ago 55
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:

//do something

//do something
is executed even if

I noticed that this works:

//do something

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

Answer Source

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...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download