How can I limit the max value of number?

后端 未结 9 2054
小蘑菇
小蘑菇 2021-01-19 11:09

I want to secure my page by checking if the value is digital (0,1,2,3) and if it is in the range from 0 to 120. I think ctype_digit function limits numbers, so

9条回答
  •  遇见更好的自我
    2021-01-19 11:25

    Here's a simple way:

    function set_range($value, $minimum, $maximum) {
        return min(max($minimum, $value), $maximum);
    }
    

    Here's what we're doing:

    1. compare the number with our minimum value, and take the highest number.
    2. compare that result with our maximum value, and take the lowest number.

    And here's a test:

    // Check every fifth number between 0-60 and 
    // set output to within range of 20 to 40.
    //
    for ($i = 0; $i < 60; $i += 5) {
        echo $i . " becomes " . set_range($i, 20, 40) . PHP_EOL;
    }
    

    If you want to check if a number is within a range, you could do this:

    function in_range($value, $minimum, $maximum) {
       return ($value >= $minimum) && ($value <= $maximum);
    }
    
    echo (in_range( 7, 20, 40)) ? "yes" : "no";  // output: no
    echo (in_range(33, 20, 40)) ? "yes" : "no";  // output: yes
    

提交回复
热议问题