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
2010-08-21 01:51:08
Sweet! Thanks so much!
Leticia Meyer
2010-08-21 01:51:37
@Leticia: You should also post your code next time so we can see where you went wrong.
casablanca
2010-08-21 01:52:34
@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
2010-08-21 01:53:07
+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
2010-08-21 01:53:22
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
2010-08-21 01:59:32
cHao
2010-08-21 02:06:12