How can I put a negative number in PHP? [closed]

-2

That is, I have a variable x.

$x = 2;

What would be the command to get the $x = -2 ?

    
asked by anonymous 02.10.2016 / 03:23

4 answers

3

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

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

$x = retornaNegativo(2);

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

02.10.2016 / 03:34
2

Any negative number with a positive, turns negative

Multiply by -1

$ x * = -1;

    
02.10.2016 / 05:24
2

Just match as the negative sign on the front:

$x = 2;
$x = -$x;
    
03.10.2016 / 14:18
1

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

$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;

    
02.10.2016 / 12:25