Re: [RFC] [Discussion] Add clamp function
| From: | Tim Düsterhus | Date: | Thu, 28 Aug 2025 07:37:43 +0000 |
| Subject: | Re: [RFC] [Discussion] Add clamp function | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-128580@lists.php.net to get a copy of this message | ||
Hi
Am 2025-08-28 08:35, schrieb Hans Krentel:
This also highlights a minor but important clarification for the documentation. To make the behavior perfectly unambiguous, I suggest a small edit to explicitly state the bounds are inclusive.This is a good point and I agree that it should be spelled out explicitly. However to me this also raises the question if the interval boundaries should be configurable to switch between closed intervals and (half-)open intervals. For many applications of continuous values a right-open interval (excluding the upper boundary) is more useful, since this makes it easy to generate non-overlapping ranges (e.g. to clamp to a given day when passing DateTimeImmutable). This would also provide an additional value-add over the min-max construction, where the boundaries would need to be calculated manually, which is super complicated to do in userland for floats. There's precedent in ext/random with the Randomizer::getFloat() method that takes a Random\IntervalBoundary enum to decide on the the interpretation of the boundary values. Translated to
clamp() this could mean:
$value = 1.0;
clamp($value, 0.0, 1.0, IntervalBoundary::ClosedOpen); // 0.999999999999999888978
Best regards
Tim Düsterhus