tags:

views:

40

answers:

3

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?

A: 
too much php
+1  A: 
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).

Amber
A: 

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

alex