简体   繁体   中英

Check if variable is different from several values

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!

if (($var != 0) && ($var != 1) && ($var != 2)) {
    //...
}

or...

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

See logical operators .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM