kerry kerry - 1 month ago 7
PHP Question

php function to return the difference between 2 numbers as a positive value

I have googled, yahooed and researched SO but no luck. I am trying to compare 2 numbers using php. I can obviously use if statement to see if the 2 numbers are equal in which case the result would be 0. I can also use if statement to see which is largest and subtract the smaller number and I can use if statement to see if either or both numbers are negative. But I wondered if there was a more elegant solution.

Examples

3,1 would return 2

-1, -2 would return 1

-3, 3 would return 6

Thanks

Answer

As pointed out by @Phylogenesis, you can use the abs() function. For example:

$var1 = -2;
$var2 = -30;

echo abs($var1 - $var2); // 28

You could also define your own function:

function diff($v1, $v2) {
    return ($v1-$v2) < 0 ? (-1)*($v1-$v2) : ($v1-$v2);
}
echo diff(-2, -30); // 28
Comments