How to Always Return a Negative Number in PHP?

Converting positive numbers to negative and leaving negative numbers unchanged

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

Hope you found this post useful. It was published . Please show your love and support by sharing this post.