How to convert a negative number to a positive number with PHP

Converting a number from negative to positive is a pretty simple process using
the absolute function abs():

$positive = abs(-123); // = 123
$positive = abs(123);  // also = 123
PHP

Absolute returns a positive integer or float based on what you feed it.
Because it only ever returns a positive value, you don’t have to worry about
what number is going in (as long as it’s a number).

This all being said, another way to convert a negative to a positive would be to
multiple it by -1:

$positive = -123 * -1; // = 123
$positive =  123 * -1; // = -123
PHP

The only caveat is that if you are working with a positive number, it will
become negative as well as converting the negative to a positive. This can
easily be accomplished by sanity checking the variable before you multiply it:

$value = -123;

if ($value < 0) {
    $value = $value * -1;
}
PHP

A bit more typing, but ensures we don’t convert a positive to a negative (unless
that’s what you were going for).

I went ahead and took this idea further and ran both scenarios to see which was faster. As expected, even with the conditional, just multiplying the number by -1 was around 235% faster over 1 million iterations on my iMac (results my vary on your own server though).

Typically speaking, simple statements in PHP tend to run faster than function
calls. At the end of the day, the different was negligible unless you are converting billions of values and even then there may be a better way to
accomplish this at that volume.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.