Did you know?
PHP 8.6 adds clamp(), which keeps a value inside a range in one call.
Replace max($min, min($max, $v)) with clamp($v, min: 0, max: 100). It throws a ValueError if min is greater than max.
- Web servers
- Applies to PHP 8.6 and later
- Last checked
Explained
Limiting a number to a range is one of the most common bits of code in any app: page numbers, percentages, quantities, retry counts. Until now PHP had no function for it, so everyone wrote the same nested call, which is easy to get backwards:
$percent = max(0, min(100, $value));PHP 8.6 adds clamp(), which takes the value, the lower bound and the upper bound. Named arguments make the call read clearly:
clamp(42, min: 0, max: 100); // 42
clamp(150, min: 0, max: 100); // 100
clamp(-5, min: 0, max: 100); // 0It uses PHP’s normal comparison rules, so it also works with strings and DateTime objects, for example to keep a date inside a booking window. Unlike the max(min()) trick, it catches mistakes: if min is greater than max, or either bound is NAN, it throws a ValueError instead of quietly returning a wrong value.
If your code must still run on PHP 8.5 or older, keep the old pattern or wrap it in a small helper with the same name behind function_exists('clamp').
Learn more
- PHP 8.6 Released: Partial Function Application, clamp() and Time\Duration Full guide · Updated Nov 2026
