php logical operator comparison evaluation -


here i'm trying achieve:

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

i'm doing this:

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

but //do something executed if $x 400

i noticed works:

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

how first block of code different second block of code? doing wrong?

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

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

is true because expression contains @ least 1 truthy value.

so, rhs of expression true, while lhs truthy value, therefore entire expression evaluates true. the reason why happening because of == operator, loose comparison. if used ===, resulting expression false. (unless of course value of $x false-y.)

let's analyze this:

assuming $x equal '400':

  ($x == ('100'||'200'||'300'))  //  ^            ^ // true         true 

make sense now?

bottom line here is: this wrong way of comparing 3 values against common variable.

my suggestion use in_array:

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

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -