clamp()
Polyfill for clamp() function added in PHP 8.6.
Clamps a value to be within the range of a given minimum and maximum.
If the value is within the bounds, the original value is returned. If it is not within the bounds, the closest bound is returned.
No Hooks.
Returns
mixed. The clamped value. Either $value, $min, or $max.
Usage
clamp( $value, $min, $max );
- $value(mixed) (required)
- The value to clamp.
- $min(mixed) (required)
- The minimum bound. Must be less than or equal to
$max. - $max(mixed) (required)
- The maximum bound. Must be greater than or equal to
$min.
Changelog
| Since 7.1.0 | Introduced. |
clamp() clamp code WP 7.1
function clamp( $value, $min, $max ) {
$throw_value_error = static function ( string $message ) {
// The ValueError class was introduced in PHP 8, so in 7.4 throw InvalidArgumentException instead.
if ( ! class_exists( 'ValueError', false ) ) {
throw new InvalidArgumentException( $message );
}
throw new ValueError( $message );
};
if ( is_float( $min ) && is_nan( $min ) ) {
$throw_value_error( 'clamp(): Argument #2 ($min) must not be NAN' );
}
if ( is_float( $max ) && is_nan( $max ) ) {
$throw_value_error( 'clamp(): Argument #3 ($max) must not be NAN' );
}
if ( $max < $min ) {
$throw_value_error( 'clamp(): Argument #2 ($min) must be smaller than or equal to argument #3 ($max)' );
}
/*
* The upper bound is checked before the lower bound to match the order in PHP's
* implementation. Comparison in PHP is not transitive when operands of different
* types are mixed (for example, comparing against a bool coerces both operands to
* bool), so both bounds can compare as exceeded at once, and the first check wins.
*/
if ( $value > $max ) {
return $max;
}
if ( $value < $min ) {
return $min;
}
return $value;
}