wpseek.com
A WordPress-centric search engine for devs and theme authors
clamp › WordPress Function
Since7.1.0
Deprecatedn/a
› clamp ( $value, $min, $max )
| Parameters: (3) |
|
| Returns: |
|
| Defined at: |
|
| Codex: |
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.Related Functions: clean_pre
Source
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;
}
}