I need a simple script that reads a number from POST (we'll call the value 'number'). It will be a three digit number that must range from the following:
301-340
401开发者_开发百科-440
501-540
601-640
701-740
801-840
If it doesn't fall in these ranges, I need to echo a message. How would one do this?
if($number <= 300 || $number > 840 || (($number-1) % 100) >= 40) {
echo "Number was not in ranges!";
}
This takes advantage of the %
(modulo) operator which returns the remainder when dividing by a number - so since you're wanting numbers where the remainder modulo 100 is 1-40, it can just subtract one, take it modulo 100, and then see if that is 40+ (since 1-40 is now 0-39).
This approach is nice and concise, as long as your ranges follow that set pattern. If you need more customization of the individual ranges, use a switch
statement (see the answer from "too much php" for an example of this).
$n = (int)$_POST['number']; switch(true) { case $n >= 301 && $n <= 340: case $n >= 401 && $n <= 440: case $n >= 501 && $n <= 540: // ETC // number is OK, break out of switch break; default: echo "Number '$n' is invalid!<br />"; exit; }
This one is a bit different. Hopefully the array building doesn't add too much overhead.
// Possible answers
$validInputs = array_merge(range(301, 340), range(401, 440), range(501, 540)); // and so forth...
$input = (int) $_POST['input'];
if ( ! in_array($input, $validInputs)) {
echo 'Got an error!';
}
Relevant docs: range(), array_merge() and in_array().
精彩评论