Greetings internals,

I present to you a proposal for a new basic math function: clamp.

The main goal of this function is to contain a number inside a given bound.
And return the number if it is inside of that bound, and if not, and the 
number is outside of the given bound, the nearest bound is returned.

Now, does this need an RFC? The behaviour can be implemented in userland 
in a number of ways, one of which is to compare the values in a if statement.
Another is to use the min and max math functions.

max($min, min($max, $num));

I don’t have any schpeel as to why this should be in core, only that I thought 
it already was.
Considering it is part of other languages standard math library, and it is a 
useful function.

Can see this being useful in image manipulation, server-side rendering and math 
just to name few.

The proposed signature follows the convention of other math related functions.

function clamp(int|float $num, int|float $min, int|float $max): int|float {}

This function is very easy to implement, has no side effects or backward
compatibility issues, unless a userland implementation already has the function 
declared,
in which case PHP will throw a fatal error since the function cannot be 
redeclared.

I've implemented this feature a few months ago already.
- Link: https://github.com/thinkverse/php-src/pull/1 
<https://github.com/thinkverse/php-src/pull/1>

What are your opinions on this function?

Regards,
Kim Hallberg.

Reply via email to