How to check if an integer is within a range of numbers in PHP?

后端 未结 13 682
傲寒
傲寒 2020-12-04 10:57

How can I check if a given number is within a range of numbers?

13条回答
  •  一个人的身影
    2020-12-04 11:31

    You could whip up a little helper function to do this:

    /**
     * Determines if $number is between $min and $max
     *
     * @param  integer  $number     The number to test
     * @param  integer  $min        The minimum value in the range
     * @param  integer  $max        The maximum value in the range
     * @param  boolean  $inclusive  Whether the range should be inclusive or not
     * @return boolean              Whether the number was in the range
     */
    function in_range($number, $min, $max, $inclusive = FALSE)
    {
        if (is_int($number) && is_int($min) && is_int($max))
        {
            return $inclusive
                ? ($number >= $min && $number <= $max)
                : ($number > $min && $number < $max) ;
        }
    
        return FALSE;
    }
    

    And you would use it like so:

    var_dump(in_range(5, 0, 10));        // TRUE
    var_dump(in_range(1, 0, 1));         // FALSE
    var_dump(in_range(1, 0, 1, TRUE));   // TRUE
    var_dump(in_range(11, 0, 10, TRUE)); // FALSE
    
    // etc...
    

提交回复
热议问题