To make sure that you always return a negative number in PHP, you can do either of the following:
Using Negation Operator
You can convert a number to its absolute form, and then negate it using the negation operator (-
):
-abs(n)
This would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use it in the following way:
function neg(int|float $num): int|float { return -abs($num); } var_dump(neg(1234)); // -1234 var_dump(neg(-1234)); // -1234
Using Arithmetic Operators
You can convert the number to its absolute form, and then negate it either by:
- Multiplying or dividing the number by
-1
, or; - Subtracting the number from
0
.
abs(n) * -1
abs(n) / -1
0 - abs(n)
This would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use these in the following way:
function neg(int|float $num): int|float { return abs($num) * -1; } var_dump(neg(1234)); // -1234 var_dump(neg(-1234)); // -1234
function neg(int|float $num): int|float { return abs($num) / -1; } var_dump(neg(1234)); // -1234 var_dump(neg(-1234)); // -1234
function neg(int|float $num): int|float { return 0 - abs($num); } var_dump(neg(1234)); // -1234 var_dump(neg(-1234)); // -1234
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.