Jump to content

inside a WHILE using $i with a variable


curtm

Recommended Posts

I have 60 days of deposits.  I want to show a list of what each days deposit, plus the previous day, plus the next day equals.

 

I could write like this...

$day1 = $day0 + $day1 + $day2;
echo "1 - ";
echo $day1;
echo "<br>";

for each day, but I'm lazy and time is short.

 

How do I do this...

 

$x=2;
$times = 59;

while ($x < $times) {
$prev = $x-1;
$next = $x+1;
$deposit = $day$x + $prev + $next;
echo $x;
echo " - ";
echo $deposit;
echo "<br>";
++$x;
} 

 

The

$day$x

is where I'm having problems.

 

thanks

Link to comment
https://forums.phpfreaks.com/topic/98885-inside-a-while-using-i-with-a-variable/
Share on other sites

I think an array is the way forward here.

 

$day[0] would be first day, $day[1] would be the 2nd etc, then it would be a case of

 

$x=2;
$times = 59;

while ($x < $times) {
$prev = $x-1;
$next = $x+1;
$deposit = $day[$x] + $day[$prev] + $day[$next];
echo $x;
echo " - ";
echo $deposit;
echo "<br>";
$x++;
}

You will have to change all the day values further up in the script so that the variables work, ie

 

$day = array();

 

$day[0] = "DAy 1 Deposits";

$day[1] = "Day 2 Deposits";

...

 

instead of

 

$day0 = "Day 1 deposits";

$day1 = "Day 2 Deposits";

...

 

which you will probably have now.

It says it's undefined because you have to set it some value.

 

What's $day[$x]  ????

 

Try this fix ... Pseudo-code (didn't check the rest, just the undefined $day variable ...)

 

$x=2;
$times = 59;

while ($x < $times) {
$prev = $x-1;
$next = $x+1;

$day[$prev] = isset($day[$prev]) ? $day[$prev] : 0;
$day[$next] = isset($day[$next]) ? $day[$next] : 0;
$day[$x] = isset($day[$x]) ? $day[$x] : 0;



$deposit = $day[$x] + $day[$prev] + $day[$next];
echo $x;
echo " - ";
echo $deposit;
echo "<br>";
$x++;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.