Jump to content

increment variable and days


Tanja

Recommended Posts

For an calender i want to have date(s) in a loop.

 

$due_date is given as YYYY-mm-dd, like 2013-11-01

for example, day 15 is created with

$days15 = strtotime('+15 days', $due_date);

and called

echo date('Y-m-d', $days15);

I tried following (not all together, each for each)

for ($i=1; $i <= 70; $i++)
{
$days.$i = strtotime("+".$i." days", $due_date);
${'days' .($i)} = strtotime(+$i." days", $due_date);
${'days' .($i)} = strtotime($due_date + $i .'days');

${'days' .($i)}= strtotime($i++." days", $due_date);
}

 

but i get wrong dates (like 1970-01-08 or 2014-01-08)

What i´m doing wrong?

 

Link to comment
https://forums.phpfreaks.com/topic/284814-increment-variable-and-days/
Share on other sites

1. Turn $due_date into a Unix timestamp (strtotime() it if there isn't a more direct method)

2. Use strtotime() as you did in the first attempt

3. Don't try to use fancy variables like "$days1" but instead use a $days array if you absolutely must have all 70 values at the same time (which I doubt you do)

Hi Tanja,

one problem I noticed in your for loop

 


for ($i=1; $i <= 70; $i++)
{
$days.$i = strtotime("+".$i." days", $due_date);
${'days' .($i)} = strtotime(+$i." days", $due_date);
${'days' .($i)} = strtotime($due_date + $i .'days');

${'days' .($i)}= strtotime($i++." days", $due_date);
}

 

I'm not sure how PHP restrictions on variable scoop works exactly, but it seems like all ${'days'.($i)} variables created won't survive the for loop scoop, here is a work around I made :

$differences = array();
$dueDate = '2013-01-01';
for ($i=1; $i <= 70; $i++) {
    $timeDate = new DateTime($dueDate);
    $timeDate->add(new DateInterval('P'.$i.'D'));
    $differences['days'.$i] =  $timeDate->format('Y-m-d');
}
var_dump($differences);

All new dates will be stored in the differences array.

 

For example, if we reset $i <= 70 to $i <= 5 we have :

 

 

Array (
'days1' =>  '2013-01-02' ,
'days2' => '2013-01-03' ,
'days3' => '2013-01-04' ,
'days4' => '2013-01-05' ,
'days5' => '2013-01-06'

)

 

Hope this helps.

If you are going to use DateTime class then use DatePeriod class to make the array

$dt = new DateTime('2013-11-01');
$di = new DateInterval('P1D');
$dp = new DatePeriod($dt,$di,70);

foreach ($dp as $d) echo $d->format('Y-m-d').'<br>';

results

2013-11-01
2013-11-02
2013-11-03
2013-11-04

.
.
.

2014-01-07
2014-01-08
2014-01-09
2014-01-10

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.