PHP 8.6’s clamp() Will Clean Up Your Code!
Even though we just got PHP 8.5, work is already underway for PHP 8.6. One of the features that’s been approved and looks like we’ll most likely get is the clamp() function.
It’s a simple function, but it’s really going to make our code a lot easier to maintain.
The RFC says that:
`clamp` checks if a comparable 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.
This means that we can use clamp() to make sure a variable fits within a specific range.
My favorite example for this is making sure a percentage isn’t greater than 100 or less than 0. We can do this currently in user space using something like the following:
$clamped = $percentage;
if ($clamped > 100) {
$clamped = 100;
}
if ($clamped < 0) {
$clamped = 0;
}
We can do this using the clamp() function like so:
$clamped = clamp($percentage, 0, 100);
It’s not a HUGE improvement, but it does reduce the chance we mess up the `if` blocks.
Some other examples from the RFC include:
clamp(2, min: 1, max: 3) // 2
clamp(0, min: 1, max: 3) // 1
clamp(6, min: 1, max: 3) // 3
clamp(2, 1.3, 3.4) // 2
clamp(2.5, 1, 3) // 2.5
clamp(2.5, 1.3, 3.4) // 2.5
clamp(0, 1.3, 3.4) // 1.3
clamp(M_PI, -INF, INF) // 3.141592653589793
Where it gets interesting is the fact that we can use this on things that aren’t numbers.
Like strings:
// taken from the RFC
clamp(”a”, “c”, “g”) // “c”
clamp(”d”, “c”, “g”) // “d”
And even `DateTimeImmutable`s.
// taken from the RFC
clamp(
new \DateTimeImmutable(’2025-08-01’),
new \DateTimeImmutable(’2025-08-15’),
new \DateTimeImmutable(’2025-09-15’)
)->format(’Y-m-d’) // 2025-08-15
clamp(
new \DateTimeImmutable(’2025-08-20’),
new \DateTimeImmutable(’2025-08-15’),
new \DateTimeImmutable(’2025-09-15’)
)->format(’Y-m-d’) // 2025-08-20
If max and min are “incorrect,” we’ll get a `ValueError`
// taken from the RFC
clamp(4, 8, 6)
// Throws ValueError: clamp(): Argument #2 ($min) must be smaller than or equal to argument #3 ($max)
clamp(4, NAN, 6)
// Throws ValueError: clamp(): Argument #2 ($min) cannot be NAN
clamp(4, 6, NAN)
// Throws ValueError: clamp(): Argument #3 ($max) cannot be NAN
I’m looking forward to adding this to my toolbox of helpful built-in functions.


