Converting a number from negative to positive is a pretty simple process using
the absolute function
Absolute returns a positive
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:
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:
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.