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 42Checking 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)