PHP Code to Check if a Variable is Between Two Numbers

While coding, the validity of an inequality is often required. In simple words, you need to check if the value if a given variable is between two other numbers,

100 < $var < 150

But if you directly write this in PHP if statement, you will get a buggy statement. This is because when this expressions will be evaluated (from left to right), first you will get a 1 (true) or 0 (false), depending upon the value stored in the variable $var. But then you will always get 1 or true, because 0 or 1 is always less then the next number 150.

The correct php code to check if a variable is between two numbers is this,

($var < 100) && ($var <= 150)

This will result in correct output as the code in parentheses will be evaluated first.

If you need to check if a variable is between two numbers very often, then you can also use the following function to check the validity of inequality,

function nBetween($varToCheck, $high, $low) {
if($varToCheck < $low) return false;
if($varToCheck > $high) return false;
return true;
}

You can then simply call this function as needed,

if (numberBetween(35, 100, 20)) {
echo 'The number is in the range!';
} else {
echo 'The number is outside the range!';
}

Leave a Comment