How can I put a negative number in PHP?

Asked

Viewed 3,793 times

-2

I mean, I have a variable x.

$x = 2;

What would be the command so you could put the $x = -2?

  • 4

    Exactly this. There seems to be no question here, so if there is no clarification it would be better to close as unclear to avoid ambiguities of interpretation, as is already occurring.

  • 2

    Read Bruno Pitelli’s answer. If you want to apply this programmatically, it’s the ideal medium. Multiply by -1.

  • Thank you @Gonçalo

4 answers

2


You can create a method to always return the negative value of a number:

function retornaNegativo($valor){
    return -abs($valor);
}

$x = retornaNegativo(2);

The function abs always returns the value without the sign, then independent of the number passed as parameter to the function returnNegative, the return will always be negative.

2

Any negative number with a positive turns negative

Multiply by -1

$x *= -1;

2

Just match as the negative sign on the front:

$x = 2;
$x = -$x;

1

If you want to turn an existing variable into a negative value, programmatically multiply by -1. This is basic mathematics.

$x = 10;

/*
aqui faz as firulas e tal..

*/

//em algum ponto vc quer mudar o $x para negativo, então use

$x *= -1;

When the value is variable, this is the correct form.

If the value is constant or already starts with negative, then just do the obvious

$x = -10;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.