Home » Php » is there a php function to return the difference between any 2 integer numbers as a positive integer?

is there a php function to return the difference between any 2 integer numbers as a positive integer?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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

Answer:

Use the absolute value function of php of the difference of the two numbers.

$answer = abs($num1 - $num2);