If not or statements
Very simple question... I'm having an issue that an if statement isn't working? All I want is the statement to be that if when $quantity is not equal to 20, or 40, or 80, or 160 to display here.
if($quantity != '20' || $quantity !='40' || $quantity != '80' || $quantity != '160')
{
echo "here";
}
Any suggestions would be ap开发者_Python百科preciated. :)
Try this, it's cleaner (IMO) :
if (!in_array($quantity, array(20, 40, 80, 160))
{
echo "here";
}
Else just replace ||
with &&
.
replace the || (or) by && (and) ;)
This way you check if something is 20, then you check if something is 40, etc. So when you have for example 40 the first check (!=20) just returns True (since you are using or's) and it never reaches the second or further check.
If $quantity
is 40, it is not 20, so the condition is satisfied.
Study and understand http://en.wikipedia.org/wiki/De_Morgan%27s_Law .
If you don't want $quantity to be equal to any of them, you need to change your '||' or operator to the and operator '&&'.
I made it easier to check for higher numbers, by figuring out your algorithm.
Iterative:
<?php
for ($i = 0; $i <= 3; $i++) {
if ($quantity == pow(2,$i)*20) { echo "not here"; goto matched; }
}
echo "here";
matched:
?>
More functional:
<?php
if (!in_array($quantity,
array_map(
function ($i) { return pow(2,$i)*20; },
range(0,3)
)
)) {
echo "here";
} else {
echo "not here";
}
?>
精彩评论