PHP: Return previous value of the "for" loop variable

Asked

Viewed 76 times

1

I have a "for" loop in PHP as follows

$max = 10; 

for($i = 0; $i <= $max; $i++){
  $var1 = $i * 100;
  $var2 = var1  * 50;
  $var3 = (MINHA_DUVIDA_AQUI);
}

In $var3 I would like to return the value of $var3 of Row previous, for example, if I am in $i = 3, I need the $var3 be equal to $var2 of $i = 2.

I tried with the function prev(), but for not being a array didn’t work.

Any tips on how to resolve this situation?

  • You can make $var2 = ($i-1) * 50. That would be your problem from what I understand.

  • You only need to treat this situation when $i = 0. In this case I don’t know what you want to return, but you can check if $i == 0 then $var2 = 0, and if it’s not equal 0 calculate according to my comment from above.

  • The problem is that my "var2" is already the result of another calculation in the previous line

  • 1

    Just make $var3 = $var2 BEFORE $var2 = formula

1 answer

5


Just do $var3 = $var2 BEFORE THE $var2 = formula

$max = 10; 
$var2 = 0;

for($i = 0; $i <= $max; $i++){
  $var3 = $var2; // Neste momento o $var2 ainda não pegou a linha atual
                 // consequentemente, terá sempre o valor da linha anterior
                 // ou zero, na primeira iteração (já que definimos zero fora do loop)
  $var1 = $i * 100;
  $var2 = $var1 * 50;

  // Agora já temos $var1, $var2 e $var3 definidos, sendo que 1 e 2 são
  // da linha corrente, e o 3 da anterior
  echo '$var1:' . $var1 . ' - $var2:' . $var2 . ' - $var3:' . $var3;
}

See working on IDEONE.

  • Thank you very much! It worked perfectly

Browser other questions tagged

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