Frage

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.

War es hilfreich?

Lösung 2

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

Andere Tipps

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));
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top