Assigned operator

2

I can not understand why it does not execute the expression I want.

Follow the code:

$i = 1; $ranking = 1; $r = 0;
for($i = 1; $i <=5; $i++){
    $p = isset($_GET["n$i"])?$_GET["n$i"]:0;
    echo "$ranking ° Numero: $p";
    $r += $p;
    $ranking++;
}

echo "A Multiplicação dos numeros é igual a : $r"

The main line of the code is $r += $p; , it adds the variables and displays in the variable $r , so alright, but if you change to $r *= $p; or $r /= $p; the result will always be 0 ( ZERO ), why?

    
asked by anonymous 05.01.2017 / 16:58

2 answers

3

How much is 0 multiplied by any value? It's 0, right? Then it is explained. Pure mathematics.

How much is 0 divided by any value? Also 0.

Programming follows the mathematical rules.

If you put 1 in $r something may come out in the multiplication, but it probably is not what you want. In the division it would probably be better to have another value, but it does not seem that changing the operator makes sense in this code. Even it can probably be simplified, so it has been introduced.

If I had a bigger context I could improve more, but it looks better this way:

$r = 0;
for($ranking = 1; $ranking <=5; $ranking++){
    $p = isset($_GET["n$ranking"])?$_GET["n$ranking"]:0;
    echo "$ranking ° Numero: $p";
    $r += $p;
}

I had unnecessary variables there.

If you want to multiply:

$r = 1;
for($ranking = 1; $ranking <=5; $ranking++){
    $p = isset($_GET["n$ranking"])?$_GET["n$ranking"]:0;
    echo "$ranking ° Numero: $p";
    $r *= $p;
}

I did not even mention that this code has serious security problems because it takes a data that comes from outside and trusts that it will be right. But that's another matter.

    
05.01.2017 / 17:04
1

For those who have questions, the code looks like this.

$i = 1; $r = 1;
while($i <=5) {
    $p = isset($_GET["n$i"])?$_GET["n$i"]:0;
    echo "$i ° Numero: $p <br>";
    $r *= $p;
    $i++;
}


echo "<br>A Multiplicação dos numeros é igual a : ".($r-1);
    
05.01.2017 / 17:40