I have googled, yahooed and researched SO but no luck. I am trying to compare 2 numbers using PHP.
To be clear I know I can accomplish this using basic maths and maybe a simple
if{}
I know how to do this, I could write a simple function, finding the result but this is not my question.
My question is simply - Is there a PHP function to return the difference between 2 integer numbers, +ve or -ve presented in any order as a positive integer
Example
PHPFunction(3,-2) result 5
Thanks
$sum = $number1-$number2; echo "The difference of $number1 and $number2 is: ". $sum; }
By using abs() function we can get the difference of two integer numbers without comparing them, abs() is a library function which is declared in stdlib. h – This function returns the absolute value of given integer.
The abs() function is an inbuilt function in PHP which is used to return the absolute (positive) value of a number. The abs() function in PHP is identical to what we call modulus in mathematics. The modulus or absolute value of a negative number is positive.
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 abs_diff($v1, $v2) {
$diff = $v1 - $v2;
return $diff < 0 ? (-1) * $diff : $diff;
}
echo abs_diff(-2, -30); // 28
Use the absolute value function of php of the difference of the two numbers.
$answer = abs($num1 - $num2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With