How to check if an integer is within a range?

dynamic picture dynamic · Feb 17, 2011 · Viewed 138.4k times · Source

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?

Answer

Mark Paspirgilis picture Mark Paspirgilis · Jul 21, 2013

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);
}