Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to clamp a number to a range

Short answer

Nest min() inside max(): the first caps from above, the second from below:

<?php
 
function clamp(int $value, int $min, int $max): int
{
    return max($min, min($max, $value));
}
 
echo clamp(150, 1, 100), ' ', clamp(-5, 1, 100), ' ', clamp(42, 1, 100);

Output:

100 1 42

Checking without changing

If you only need to know whether the number is within the range:

<?php
 
$age = 25;
 
var_dump($age >= 18 && $age <= 65);

Output:

bool(true)

Functions used in this recipe

  • min — Returns the smallest of the values.
  • max — Returns the largest of the given values.

Thanks for reading!

Donate to the site — we work hard for you.