Is there a (simple) way to get the "sign" of a number (integer) in PHP comparable to gmp_sign
Docs:
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
Get the Sign of Elements of a Numeric Vector in R Programming – sign() Function. sign() function in R Language is used to find the sign of the elements of the numeric vector provided as argument.
sign() in Python. numpy. sign(array [, out]) function is used to indicate the sign of a number element-wise. For integer inputs, if array value is greater than 0 it returns 1, if array value is less than 0 it returns -1, and if array value 0 it returns 0.
Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are identical.
Here's a cool one-liner that will do it for you efficiently and reliably:
function sign($n) { return ($n > 0) - ($n < 0); }
In PHP 7 you should use the combined comparison operator (<=>
):
$sign = $i <=> 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With