Probably a dumb question but is there a more clever way of checking that an image 1360x455 is within the allowed tolerance of say +-10 of two other numbers I have defined? :
<?php
$w = 1360;
$h = 455;
$cw = 1360;
$ch = 460;
$tol = 10; //px
if ((int) $w >= (int) ($cw-$tol) && (int) $w <= (int) ($cw+$tol) &&
(int) $h >= (int) ($ch-$tol) && (int) $h <= (int) ($ch+$tol)) {
echo "you are within the tolerance {$cw}x{$ch}px by +-{$tol} px.";
};
So I basically just want to make sure the user doesn't go outside of these bounds when uploading. The above code works, just wondering if I could be more clever about it. The method already knows these values as they are passed in.
A more concise method would be to subtract the input value against the reference and ensure the absolute value (abs()
) of the result is less than or equal to your tolerance.
The difference between the reference value an input value must be within 10, and subtracting them will produce a positive or negative integer. Using abs()
strips its sign, so it's a simple <=
comparison with the tolerance value.
$w = 1360;
$h = 455;
$cw = 1360;
$ch = 460;
$tol = 10; //px
if (abs($cw - $w) <= $tol && abs($ch - $h) <= $tol) {
echo "you are within the tolerance {$cw}x{$ch}px by +-{$tol} px.";
}
The casting with (int)
is generally unnecessary here. But if your function may be receiving string values, I would suggest casting the variables to ints before the calculation just so to reduce clutter.