clamp
checks if a int|float
value is within a certain bound. If the value is in range it returns the value, if the value is not in range it returns the nearest bound.
Current userland implementations are handled in several ways, some of which use min and max to check the bound, which is costly and slow when called often. Because userland implementations are for the most part not cost-effective when called multiple times, a language implementation is desired.
This RFC proposes a new function: clamp
clamp ( int|float $num, int|float $min, int|float $max ) : int|float
clamp
takes three arguments, a $num
, $min
and $max
, checks if $num
is within the bounds of $min
and $max
, if in range, returns the value of $num
, otherwise, returns the nearest bound value, i.e. if $num > $max
return $max
, if $num < $min
return $min
.
If $min
value is greater than $max
value, a ValueError
will be thrown, since that constitute an invalid bound.
The proposed function as code:
clamp(num: 1, min: 0, max: 3); // 1 in range clamp(num: 1, min: 2, max: 5); // 2 < bound clamp(num: 4, min: 1, max: 3); // 3 > bound clamp(num: 0, min: 2, max: 1); // clamp(): Argument #2 ($min) cannot be greater than Argument #3 ($max)
Handling NAN; passing NAN to either of the range values will throw above ValueError
since passing NAN will invalidate the range.
No backwards incompatible changes with PHP itself.
clamp
will no longer be available as a function name, could break potential userland implementations.
The vote will require 2/3 majority.
RFC implementation can be found in the following pull request: https://github.com/php/php-src/issues/7191.
No rejected features currently.