I find that I frequently end up writing a function that I always call "clamp()
", that is kind of a combination of min()
and max()
. Is there a standard, "canonical" name for this function?
It always looks something like this:
function clamp($val, $min, $max)
{
if ($val < $min)
return $min;
else if ($val > $max)
return $max;
else
return $val;
}
Or simply using built-in min()
and max()
functions:
function clamp($val, $min, $max)
{
return max($min, min($max, $val));
}
Variations exist: You can also check for invalid input, where min > max
, and either throw an exception or reverse the inputs. Or you can ignore order of the inputs and call it a median-of-three function, but that can be confusing.