Since PHP 8.6, the clamp function is available, which limits a value to a given range. A value below the range becomes the minimum, a value above the range becomes the maximum, and a value inside the range is returned unchanged. Before PHP 8.6, the same result required nesting min and max, such as max(10, min(100, $value)).
The following code limits values of different types to a range:
<?php
echo clamp(5, min: 10, max: 100); // 10
echo clamp(50, min: 10, max: 100); // 50
echo clamp(500, min: 10, max: 100); // 100
echo clamp(3.7, min: 1.0, max: 10.0); // 3.7
echo clamp('m', min: 'a', max: 'f'); // f
The function works with integers, floats and strings. Strings are compared the same way as with the comparison operators.
All three arguments are required. The named arguments are optional, so clamp(5, 10, 100) returns the same result, but naming them makes clear which bound is which.
If the lower bound is greater than the upper bound, a ValueError is thrown:
<?php
echo clamp(5, min: 100, max: 10); // Fatal error: Uncaught ValueError
Leave a Comment
Cancel reply