Usage
Functions
clamp()
clamp(mixed $value, mixed $min, mixed $max): mixed
Returns $value clamped to the range [$min, $max]. This is the recommended function — it uses direct comparisons and is the faster of the two implementations.
clampMinMax()
clampMinMax(mixed $value, mixed $min, mixed $max): mixed
Equivalent to clamp() in every way, including accepted types and error behaviour. It uses the max($min, min($max, $value)) approach internally and runs about 2× slower. See Performance for details.
Accepted types
Arguments may be integers, floats, strings, or any objects that support comparison (e.g. DateTimeInterface). Mixed numeric types are allowed.
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(0, 1.3, 3.4); // 1.3
clamp(M_PI, -INF, INF); // 3.141592653589793
clamp(NAN, 4, 6); // NAN — NAN is returned unchanged
clamp("a", "c", "g"); // "c"
clamp("d", "c", "g"); // "d"
clamp(
new DateTimeImmutable('2025-08-01'),
new DateTimeImmutable('2025-08-15'),
new DateTimeImmutable('2025-09-15')
)->format('Y-m-d'); // "2025-08-15"
Errors
A ValueError is thrown when the bounds are invalid. Both functions behave identically.
Invalid range — $min must be less than or equal to $max:
clamp(4, 8, 6);
// ValueError: clamp(): Argument #2 ($min) must be smaller than or equal to argument #3 ($max)
NAN bounds — NAN is not allowed as a bound (only as the value):
clamp(4, NAN, 6);
// ValueError: clamp(): Argument #2 ($min) cannot be NAN
clamp(4, 6, NAN);
// ValueError: clamp(): Argument #3 ($max) cannot be NAN