Can some help, don’t know how to solve this using loop in PHP
$pay = [20, 40 , 89, 300, 190, 15]; <br/> $Capital = 1000; <br/>
I want the loop to achieve this result
1000-20 = 980 <br/> 980-40 = 940 <br/> 940-89 = 851 <br/> 851-300 = 551 <br/> 551-190 = 361 <br/> 361-15 = 346 <br/>
My code is:
$newbal = $Capital-$pay <br/>
for ($amount=$newbal; $amount>=$Capital; $amount-=$pay) {
echo “{$amount} ”; <br/>
$amount++; <br/>
}
My code is giving me this result:
1000-20 = 980 <br/> 1000-40 = 960 <br/> 1000-89 = 911 <br/> 1000-300 = 700 <br/> 1000-190 = 810 <br/> 1000-15 = 985 <br/>
Advertisement
Answer
The code below, loops through the $pays array of integers.
each loop calculates the equation of $captial minus one of the integers and repeats, this is calculated and stored as a string in the $lines variable and at the end of each loop we recalculate the $capital and update the new value of $capital based on the previous calculation of capital = capital - pay
<?php
$pays = [20, 40 , 89, 300, 190, 15];
$capital = 1000;
$lines = [];
foreach($pays as $pay){
$lines[] = $capital . "-" . $pay . " = " . ($capital - $pay) . "<br/>";
$capital -= $pay;
}
echo implode("n", $lines);
?>