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

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

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

13条回答
  •  温柔的废话
    2020-12-04 11:52

    Some other possibilities:

    if (in_array($value, range($min, $max), true)) {
        echo "You can be sure that $min <= $value <= $max";
    }
    

    Or:

    if ($value === min(max($value, $min), $max)) {
        echo "You can be sure that $min <= $value <= $max";
    }
    

    Actually this is what is use to cast a value which is out of the range to the closest end of it.

    $value = min(max($value, $min), $max);
    

    Example

    /**
     * This is un-sanitized user input.
     */
    $posts_per_page = 999;
    
    /**
     * Sanitize $posts_per_page.
     */
    $posts_per_page = min(max($posts_per_page, 5), 30);
    
    /**
     * Use.
     */
    var_dump($posts_per_page); // Output: int(30)
    

提交回复
热议问题