I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
$begin = new DateTime('2010-05-01');$end = new DateTime('2010-05-10');$interval = DateInterval::createFromDateString('1 day');$period = new DatePeriod($begin, $interval, $end);foreach ($period as $dt) { echo $dt->format("l Y-m-d H:i:s\n");}
This will output all days in the defined period between $start
and $end
. If you want to include the 10th, set $end
to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod. It requires PHP 5.3.
Converting to unix timestamps makes doing date math easier in php:
$startTime = strtotime( '2010-05-01 12:00' );$endTime = strtotime( '2010-05-10 12:00' );// Loop between timestamps, 24 hours at a timefor ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) { $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc}
When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.