Clamp a PHP variable to a 0-to-4 range I have a legacy code written as below: 

if($value &lt; 0) {
    $value = 0;
}
if($value &gt; 4) {
    $value = 4;
}


Is there an easier and more elegant way to do this?
Selecting the "best" method in this case is likely going to come down to personal preference.

If you wish to use a condition-less one-liner, then insertusernamehere's offering is brief/elegant.  However, it is not instantly comprehensible for the next developer.

min(max($value, 0), 4)




If you want a one-liner with conditions (or without functions), then this is what Billal was mentioning:

$value &lt; 0 ? 0 : ($value &gt; 4 ? 4 : $value)


However, the php manual says: 


  It is recommended that you avoid "stacking" ternary expressions.




I personally find switch statements to be too clunky/verbose with the breaking.  While it is nice that it only evaluates $value once, that is of very little benefit in your tiny use case.



Finally, I recommend simply changing your second if statement to elseif so that the second statement is ignored when the first is true.  This method will be fast, clean, and instantly comprehensible.

if ($value &lt; 0) {
    $value = 0;
} elseif ($value &gt; 4) {
    $value = 4;
}


...if &gt; 4 occurs more often than &lt; 0, then reverse the order of the conditionals.

Here is a demo snippet:

$input = [-1, 0, 2, 4, 7];
foreach ($input as $value) {
    echo min(max($value, 0), 4) , "\n";
    echo $value &lt; 0 ? 0 : ($value &gt; 4 ? 4 : $value) , "\n";
    if ($value &lt; 0) {
        $value = 0;
    } elseif ($value &gt; 4) {
        $value = 4;
    }
    echo $value , "\n---\n";
}