Loop through date range of two dates in PHP

Loop through date range of two dates in PHP

Very useful when creating entries from one date to another. The basic way would be the following:

$startDate = new \DateTime('2020-06-01');
$endDate = new \DateTime('2020-06-30');

for($date = $startDate; $date <= $endDate; $date->modify('+1 day')){
    echo $date->format(\DateTime::ATOM);
}

The one I prefer would be using a period:

$startDate = new \DateTime('2020-06-01');
$endDate = new \DateTime('2020-06-30');

$interval = \DateInterval::createFromDateString('1 day');
$period = new \DatePeriod($startDate, $interval, $endDate);

foreach ($period as $date) {
  echo $date->format(\DateTime::ATOM);
}