Take actions depending on whether a number is within X percent of another
Apart from replacing the second if with an else, I would define this as a separate function:

function withinTolerance($value, $target, $tolerance) {
    return $value &gt;= $target * (1.0 - $tolerance) &amp;&amp; $value &lt;= $target * (1.0 + $tolerance);
}


Then your call can just be:

if (withinTolerance($x, 100, 0.05)) {
    // Within tolerance
} else {
    // Outside tolerance
}


I made everything one line as it's a simple expression, which should clearly indicate what it does, but you can feel free to break $target * (1.0 - $tolerance) to $min, and $target * (1.0 + $tolerance) to $max if you like.

This allows you to change the target and tolerance easily, and also has the added bonus of being reusable, and testable. (How do you go about verifying that your current version works, for example?)

You can define some simple tests:

if (withinTolerance(99, 100, 0.05)) { echo "Pass"; } else { echo "Fail"; }
if (!withinTolerance(10, 100, 0.05)) { echo "Pass"; } else { echo "Fail"; }


And so on.

You could also use a trick with the absolute value (as mentioned in comments on the question), but that takes a lot of the meaning away. This version allows you to easily define upper and lower bounds:

function withinSingleTolerance($value, $target, $tolerance) {
    return withinTolerance($value, $target, $tolerance, $tolerance);
}
function withinTolerance($value, $target, $toleranceBelow, $toleranceAbove) {
    return $value &gt;= $target * (1.0 - $toleranceBelow)
           &amp;&amp; $value &lt;= $target * (1.0 + $toleranceAbove);
}