Leticia Meyer
Leticia Meyer

Reputation: 53

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!

Upvotes: 3

Views: 12300

Answers (3)

user7675
user7675

Reputation:

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

Upvotes: 0

Artefacto
Artefacto

Reputation: 97815

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

or...

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

See logical operators.

Upvotes: 7

cHao
cHao

Reputation: 86506

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

Upvotes: 5

Related Questions