min() And max() For Interval

By Povilas Korop

../_images/min-max.png

PHP trick: min-max a number in one line.

Need a value inside a range between 0 and 1?

Just nest min() and max(): max(0, min($value, 1)).

It pins all below 0 up to 0 and all above 1 down to 1.

Of course, if-else statement may look more readable, if you prefer :)

Addendum: future PHP 8.6 will have clamp() function for that purpose.

Addendum 2: min and max may be swapped, along with their literal, with the same effect.

Addendum 3: it also works on strings.

See Also

PHP Features