How to check if an integer is within a range?

前端 未结 8 754
轻奢々
轻奢々 2020-11-28 07:35

Is there a way to test a range without doing this redundant code:

if ($int>$min && $int<$max)

?

Like a function:

相关标签:
8条回答
  • 2020-11-28 07:58

    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.

    0 讨论(0)
  • 2020-11-28 08:07

    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);
    }
    
    0 讨论(0)
提交回复
热议问题