Shamoon Shamoon - 1 year ago 63
PHP Question

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

I'm starting with 2010-05-01 and ending with 2010-05-10... how can I iterate through all of those dates?

Answer Source

Requires PHP5.3:

$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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download