How to check if an integer is within a range?
Is there a way to test a range without doing this redundant code:
if ($int>$min && $int<$max)
?
Like a function:
function testRange($int,$min,$max){
return ($min<$int && $int<$max);
}
usage:
if (testRange($int,$min,$max))
?
Does PHP have such built-in function? Or any other way to do it?
Tested your 3 ways with a 1000000-times-loop.
t1_test1: ($val >= $min && $val <= $max)
: 0.3823 ms
t2_test2: (in_array($val, range($min, $max))
: 9.3301 ms
t3_test3: (max(min($var, $max), $min) == $val)
: 0.7272 ms
T1 was fastest, it was basicly this:
function t1($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
I don't think you'll get a better way than your function.
It is clean, easy to follow and understand, and returns the result of the condition (no return (...) ? true : false
mess).
There is no builtin function, but you can easily achieve it by calling the functions min()
and max()
appropriately.
// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);
Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:
Check if $n is between $a and $b even if:
$a < $b
$a > $b
$a = $b
All numbers can be real, not only integer.
There is an easy way to test.
I base the test it in the fact that ($n-$a)
and ($n-$b)
have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.
function between($n, $a, $b)
{
return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}
I'm not able to comment (not enough reputation) so I'll amend Luis Rosety's answer here:
function between($n, $a, $b) {
return ($n-$a)*($n-$b) <= 0;
}
This function works also in cases where n == a or n == b.
Proof: Let n belong to range [a,b], where [a,b] is a subset of real numbers.
Now a <= n <= b. Then n-a >= 0 and n-b <= 0. That means that (n-a)*(n-b) <= 0.
Case b <= n <= a works similarly.