Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 272
kerry Avatar asked Oct 11 '16 08:10

kerry


People also ask

How can I get the difference between two numbers in PHP?

$sum = $number1-$number2; echo "The difference of $number1 and $number2 is: ". $sum; }

Which function returns the difference of two integers?

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.

How do I make a negative number positive in PHP?

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.


2 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
like image 123
Rax Weber Avatar answered Sep 19 '22 05:09

Rax Weber


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

$answer = abs($num1 - $num2);
like image 25
Ronald Avatar answered Sep 22 '22 05:09

Ronald