Search code examples
phpmath

How to get sign of a number?


Is there a (simple) way to get the "sign" of a number (integer) in PHP comparable to gmp_signDocs:

  • -1 negative
  • 0 zero
  • 1 positive

I remember there is some sort of compare function that can do this but I'm not able to find it at the moment.

I quickly compiled this (Demo) which does the job, but maybe there is something more nifty (like a single function call?), I would like to map the result onto an array:

$numbers = array(-100, 0, 100);
    
foreach($numbers as $number)
{
   echo $number, ': ', $number ? abs($number) / $number : 0, "\n";
}

(Example code might run into floating point precision problems probably when number is not a number or infinity etc.)

Related: Request #19621 Math needs a "sign()" function


Solution

  • Here's a cool one-liner that will do it for you efficiently and reliably:

    function sign($n) {
        return ($n > 0) - ($n < 0);
    }