PHP RFC: clamp

  • Version: 1
  • Date: 2021-06-23
  • Author: Kim Hallberg, hallbergkim@gmail.com
  • Status: Withdrawn
  • 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

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.

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

RFC Impact

  • 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.

Open Issues

1) Handling of NAN values, as mentioned #115085 and #115167.

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.


Rejected Features

No rejected features currently.

rfc/clamp.txt · Last modified: 2023/06/12 13:59 by thinkverse