Apr 25, 2011

PHP: in_range()

function in_range($num, $min, $max) {
   return ($num >= $min && $num <= $max);
}


4 comments:

Unknown said...

function in_range($num, $min, $max){
return ($num >= $min && $num <= $max);
}

Krzysiu said...

Why?! :/ Do you realize that's the most horrible way to check it? Lulu the hero gave the correct way. For your in_range, if you'd want to check between 0 and 1000000, PHP will create 1 million element array... If you really need step, which is doubtful, you could check it by using modulo operator.

Unknown said...

Holy hell, I don't even remember writing this. :D

Unknown said...

For the sake of completeness, here is the code, which has the complete functionality of the original:


function in_range($num, $low, $high, $step = 1){
if((int)$step <= 0){
return false;
}
$in = !!($num >= $low && $num < $high);
if($step !== 1){
$in = $in && (($num - $low) % $step === 0);
}
return $in;
}

var_dump(in_range(11, 3, 20, 2));


Note that in the original code, if you use the range() function, then the steps will be applied from the lowest value. So if you call range with (3, 20, 2), then the array will contain 3, 5, 7, 9, 11, 13, 15, 17 and 19. (note sure, if that is what OP wanted originally)

Also I added a !! sign to transform the numeric value of $in to a bool.

For input validation, I only check the $step parameter.