Search code examples
phpclamp

Does a "clamp" number function exist in PHP?


I wrote a function to "clamp" numbers in PHP, but I wonder if this function exists natively in the language.

I read PHP.net documentation in the math section, but I couldn't find it.

Basically what my function does is that it accepts a variable, an array of possible values, and a default value, this is my function's signature:

function clamp_number($value, $possible_values, $default_value)

If $value does not match any of the $possible_values then it defaults to $default_value

I think my function would be way faster if PHP already provides it natively because I'm using quite often in my program.


Solution

  • $value = in_array($value, $possible_values, true) ? $value : $default_value;
    

    Ref: https://php.net/in_array