In PHP, you can negate a number (i.e. convert a positive number to negative, and a negative to positive) in the following ways:
Please note that in PHP, when negating 0, the result is always 0.
Using Negation Operator
You may negate a number using the negation operator (-) like so:
-n
This would convert a positive number to a negative number, and a negative number to a positive number. For example, you can use it in the following way:
function negate(int|float $num): int|float
{
return -$num;
}
var_dump(negate(1234)); // -1234
var_dump(negate(-1234)); // 1234
var_dump(negate(0)); // 0
var_dump(negate(-0)); // 0
Using Arithmetic Operators
You may convert a positive number to negative or vice versa by simply multiplying it by -1:
n * -1
Similarly, you may also divide the number by -1 to negate it:
n / -1
You could use either of these, for example, like so:
function negate(int|float $num): int|float
{
return $num * -1;
}
var_dump(negate(1234)); // -1234
var_dump(negate(-1234)); // 1234
var_dump(negate(0)); // 0
var_dump(negate(-0)); // 0
function negate(int|float $num): int|float
{
return $num / -1;
}
var_dump(negate(1234)); // -1234
var_dump(negate(-1234)); // 1234
var_dump(negate(0)); // 0
var_dump(negate(-0)); // 0
As an alternative to dividing and multiplying by -1, you may subtract the number from 0 instead:
0 - n
For example, you could use it in the following way:
function negate(int|float $num): int|float
{
return 0 - $num;
}
var_dump(negate(1234)); // -1234
var_dump(negate(-1234)); // 1234
var_dump(negate(0)); // 0
var_dump(negate(-0)); // 0
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.