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.
It seems as though you are just trying to find a number within a set. An actual clamp function will make sure a number is within 2 numbers (a lower bounds and upper bounds). So psudo code would be clamp(55, 1, 10)
would produce 10
and clamp(-15, 1, 10)
would produce 1
where clamp(7, 1, 10)
would produce 7
. I know you are looking for more of an in_array
method but for those who get here from Google, here is how you can clamp in PHP without making a function (or by making this into a function).
max($min, min($max, $current))
For example:
$min = 1;
$max = 10;
$current = 55;
$clamped = max($min, min($max, $current));
// $clamped is now == 10
A simple clamp method would be:
function clamp($current, $min, $max) {
return max($min, min($max, $current));
}
$value = in_array($value, $possible_values) ? $value : $default_value;
I think is worth to know that...
https://wiki.php.net/rfc/clamp
Is approved and will exist in the core
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With