How to check if an integer is within a range?

前端 未结 8 821
轻奢々
轻奢々 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.

提交回复
热议问题