Thursday, April 2, 2015

How to force number returning between 2 numbers - PHP Snippet

How to force number returning between 2 numbers - PHP Snippet
Simple php function that force of returning a number between two numbers.

function clamp($number, $min, $max){ 
return max($min, min($max, $number));
}

var_dump(clamp(-10, 0, 5)); // Prints 0
var_dump(clamp(0, 0, 5)); // Prints 0
var_dump(clamp(3, 0, 5)); // Prints 3
var_dump(clamp(5, 0, 5)); // Prints 5
var_dump(clamp(10, 0, 5)); // Prints 5

Disqus Comments