Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a "clamp" number function exist in PHP?

Tags:

php

clamp

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.

like image 684
ILikeTacos Avatar asked Jul 15 '13 21:07

ILikeTacos


3 Answers

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));
}
like image 127
PhotonFalcon Avatar answered Nov 20 '22 09:11

PhotonFalcon


$value = in_array($value, $possible_values) ? $value : $default_value;
like image 42
Tim Cooper Avatar answered Nov 20 '22 08:11

Tim Cooper


I think is worth to know that...

https://wiki.php.net/rfc/clamp

Is approved and will exist in the core

like image 3
jcmargentina Avatar answered Nov 20 '22 07:11

jcmargentina