Take actions depending on whether a number is within X percent of another Let's say we had a baseline value of 100 and I have a value of X. 

If X is 5% or less higher/lower than 100 (95 to 105) then do something. If it's greater than 5% (Less than 95 or more than 105) do something else.

My initial thought was something like the below but it looks quite messy

$diff = 100*0.05;
$lower = 100-$diff;
$higher = 100+$diff;
if ($x &gt;= $lower &amp;&amp; $x &lt;= $higher) {
     // Within tolerance
}
if ($X &lt; $lower || $x &gt; $higher) {
     // Outside tolerance
}
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);
}