views:

77

answers:

3

If I want to take an action if php if a variable isn't 0,1, or 2, how would I do that? my if statement isn't working. Thanks!

+4  A: 
if (($var != 0) && ($var != 1) && ($var != 2)) {
    //...
}

or...

if (!in_array($var, array(0, 1, 2))) { /* ... */ }

See logical operators.

Artefacto
Sweet! Thanks so much!
Leticia Meyer
@Leticia: You should also post your code next time so we can see where you went wrong.
casablanca
@Let I'd advise to read a bit more about PHP before starting to write scripts. You can start here: http://www.w3schools.com/php/default.asp
Artefacto
+5  A: 

The most straightforward way:

if ($x != 0 && $x != 1 && $x != 2)
{
    // take action!
}

If you know your variable is an int, then you could also do like:

if ($x < 0 || $x > 2)
{
    // take action!
}
cHao
A: 

Use the && operator to chain tests, and test non-equality with !== which checks type and value:

if( $n !== 0 && $n !== 1 && $n !== 2 ) {
     // it's not any of those values.
}

The == operator will coerce values, so all the following are true:

  • 0 == 'foo'
  • 99 == '99balloons'
  • true == 1
  • false == ''

And so on. See comparison operators for more information about == vs. ===. Also check the table "Comparison with Various Types" to better understand how types are coerced if you are comparing non-numbers. Only you can determine if if( $n < 0 || $n > 2 ) will meet your needs. (Well, we can help, but we need more details.)

See logical operators for more on && and ||.

Adam Backstrom
cHao
Whoops, fixed. :)
Adam Backstrom