PHP RFC: clamp
- Version: 1
- Date: 2021-06-23
- Author: Kim Hallberg, firstname.lastname@example.org
- Status: Under Discussion
- Proposed Version: PHP 8.2
- First Published at: http://wiki.php.net/rfc/clamp
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 ( int|float $num, int|float $min, int|float $max ) : int|float
clamp takes three arguments, a
$max, checks if
$num is within the bounds of
$max, if in range, returns the value of
$num, otherwise, returns the nearest bound value, i.e. if
$num > $max return
$num < $min return
$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.
Backward Incompatible Changes
No backwards incompatible changes with PHP itself.
clamp will no longer be available as a function name, could break potential userland implementations.
Proposed PHP Version(s)
- next PHP 8.x
- To SAPIs: Function will be added to all PHP enviroments.
- To Existing Extensions: None
- To Opcache: None.
- New Contants: No new constants introduced.
- php.ini defaults: No changes to php.ini introduced.
Proposed Voting Choices
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.