Reputation: 53
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
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:
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
Reputation: 97815
if (($var != 0) && ($var != 1) && ($var != 2)) {
//...
}
or...
if (!in_array($var, array(0, 1, 2))) { /* ... */ }
See logical operators.
Upvotes: 7
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