Jump to content

looping over daterange


blueman378

Recommended Posts

Hi guys,

 

I'm looking to loop over a date range,

 

eg

$date = '15/03/1991';
$date2 = '21/07/2009';
$array = array();
while($date <= $date2)
{
    $array[$date]['value'] = 'somedata';
    $date.adddays(1);
}

 

obviously i know this is not going to work,

 

but other than nested loops and constant date checking for days in month/ leap year ect is there any way to do this?

 

regards,

Matt

Link to comment
https://forums.phpfreaks.com/topic/189122-looping-over-daterange/
Share on other sites

<?php
$date = '15/03/1991';
$date2 = '21/07/2009';

// unfortunately, dd/mm/yyyy is not a format that strtotime() understands
// it is also not a format that can be used in greater-than/less-than comparisons
// convert to yyyy-mm-dd
list($day,$month,$year) = explode('/',$date); 
$date = "$year-$month-$day";

list($day,$month,$year) = explode('/',$date2); 
$date2 = "$year-$month-$day";

$array = array();
while($date <= $date2)
{
    $array[$date]['value'] = 'somedata';
    $date = date('Y-m-d',strtotime("$date + 1 day"));
}
echo "<pre>",print_r($array,true),"</pre>";
?>

@pbs, Except that doing so would take approximately three times longer because the loop would need to produce the expected array index from the Unix timestamp, whereas the previously suggest solution can use the $date as the index directly.

 

$date = '15/03/1991';
$date2 = '21/07/2009';

list($day,$month,$year) = explode('/',$date); 
$date = mktime(0,0,0,$month,$day,$year);

list($day,$month,$year) = explode('/',$date2); 
$date2 = mktime(0,0,0,$month,$day,$year);

$array2 = array();
while($date <= $date2)
{
$index = date('Y-m-d',$date);
    $array2[$index]['value'] = 'somedata';
$date = strtotime("+ 1 day",$date);
}
echo "<pre>",print_r($array2,true),"</pre>";

 

Excluding the echo ... print_r() statement at the end of each piece of code, the first code typically takes 0.35317993164062 sec and the second code takes 1.1751408576965 sec. Actually using mktime() inside of the loop would take even longer than the posted code.

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.