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

后端 未结 13 596
傲寒
傲寒 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...
    
    0 讨论(0)
  • 2020-12-04 11:34

    You can try the following one-statement:

    if (($x-$min)*($x-$max) < 0)
    

    or:

    if (max(min($x, $max), $min) == $x)
    
    0 讨论(0)
  • 2020-12-04 11:36
    $ranges = [
        1 => [
            'min_range' => 0.01,
            'max_range' => 199.99
        ],
        2 => [
            'min_range' => 200.00,
        ],
    ];
    
       foreach( $ranges as $value => $range ){
            if( filter_var( $cartTotal, FILTER_VALIDATE_FLOAT, [ 'options' => $range ] ) ){
                return $value;
            }
        }
    
    0 讨论(0)
  • 2020-12-04 11:38
    if (($num >= $lower_boundary) && ($num <= $upper_boundary)) {
    

    You may want to adjust the comparison operators if you want the boundary values not to be valid.

    0 讨论(0)
  • 2020-12-04 11:49

    Might help:

    if ( in_array(2, range(1,7)) ) {
        echo 'Number 2 is in range 1-7';
    }
    

    http://php.net/manual/en/function.range.php

    0 讨论(0)
  • 2020-12-04 11:50

    using a switch case

        switch ($num){
    
            case ($num>= $value1 && $num<= $value2): 
                echo "within range 1";
            break;
            case ($num>= $value3 && $num<= $value4): 
                echo "within range 2";
            break;
            .
            .
            .
            .
            .
    
            default: //default
                echo "within no range";
            break;
         }
    
    0 讨论(0)
提交回复
热议问题