PHP DatePeriod bug
15th June 2015
I was recently working on a section of a project which involved looping through a range of dates. This was an easy task using the DatePeriod class and worked fine on my local pc. However it was producing strange results on the clients server which was running an older version of PHP.
It turns out there is a bug in early versions of PHP 5.3 when iterating through the date ranges whereby it doesn't appear to reset its pointer to the beginning. Take the following example code:
$date_from = new \DateTime('2015-06-15');
$date_to = new \DateTime('2015-06-18');
$interval = \DateInterval::createFromDateString('1 day');
$period = new \DatePeriod($date_from, $interval, $date_to);
foreach($period as $date){
echo $date->format("Y-m-d").PHP_EOL;
}
foreach($period as $date){
echo $date->format("Y-m-d").PHP_EOL;
}
Both loops should print out
2015-06-15
2015-06-16
2015-06-17
However in earlier versions of PHP 5.3 the second loop won't run.
Yes, i'm fully aware PHP 5.3 is end of line and shouldn't be used but sometimes it's just out of my control.