How to check if an integer is within a range?

前端 未结 8 817
轻奢々
轻奢々 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:49

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

提交回复
热议问题