For loop using a previous value in subsequent iteration


#1

I’m having trouble with a for loop within a function. The loop needs to utilise the result from the previous iteration on the subsequent one.

There are three arguments for the function: years, value and percentage rate. The function needs to loop through the number of years and deduct the percentage rate from the remaining level of value. So 3 years, a value of 100 and a percentage rate of 90%, should return 100, then 90 (100 less 10%), then 81 (90 less 10%). I would like to return these to an array that I can use.

My code so far:

 <?php  
function forLoop($years, $value, $rate){
     $return = $value * $rate; 
      for ($i = 0; $i < $years; $i++) {
        echo $return;
   }
}

 forLoop(3, 100, 0.90);
?>  

This gives me the right number of returns, but gives the same value for each one. I’m not sure how to ‘save’ the previous loop’s return and use it in the next iteration, nor how to return all these results to an array. I know I should know how to do this (I’ve been programming in php on and off for 2 years :flushed:), but that makes it worse! if anyone could help me I’d be very grateful. Thank you.


#2

Start with just coding it to work once. Then integrate the loop into the mix. And, “forLoop” is a horrible function name, call it what it does.


#3

Well, you only create the value ONCE in the function. You create it and then loop.
Place your value inside the loop. Simple beginner mistake. Also, you are not using the years inside your calculations so it will still always be the same.

Try something like this:

 <?php  
function forLoop($years, $value, $rate){
      for ($i = 0; $i < $years; $i++) {
          $value = $value * $rate;
        echo $i . ": " . $value . "<br>";
   }
}

 forLoop(3, 100, 0.90);
?>  

I did not user RETURN as that is a reserved word for functions. I used value alone. It changes inside each iteration. Did not test this, just adjusted off top of my head…


#4

#5

How about telling us about the real problem you are trying to solve rather than your attempt at solving it. Also, where is the data coming from in the first place?