How to get sign of a number?

hakre picture hakre · Sep 26, 2011 · Viewed 28.3k times · Source

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";
}

(this code might run into floating point precision problems probably)

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

Answer

Milosz picture Milosz · Dec 9, 2013

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

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