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


1 min read
development
php

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

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

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
$position =  123 * -1; // = -123

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)
{
	$positive = abs($value);
}

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 sanity check, 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.