Iteration over a time period in PHP

It is relatively hard to work with a list of dates on php (by days, for example) if there is a start and end of the period ($dateStart, $dateEnd). For example, to synchronize working/non-working days for the DatePicker from jQueryUi with the backend. Or if you need to display reports by days.

I suggest several options for solving this problem, both the most obvious way and a more elegant way (as it seemed to me).

Of course, you can change the date in a loop, constantly adding one day and checking the exit condition from the loop, for example like this:

<?php

$startDate = new DateTime('-1 week');
$endDate = new DateTime();

$date = clone $startDate;

while ($date <= $endDate) {
    echo "{$date->format('d-m-y')}\n";
    $date->modify('+1 day');
}

(Just an example, don't take it seriously ;))

The line $date = clone $dateStart; is needed to preserve the initial value of the $dateEnd variable, as the modify method changes the value in the object.

But there is a more elegant solution, as it seemed to me, using DatePeriod and DateInterval:

<?php

$startDate = new DateTime('-1 week');
$endDate = new DateTime();
$period = new DatePeriod($startDate, new \DateInterval('P1D'), $endDate->modify('+1 day'));

foreach ($period as $date) {
    echo "{$date->format('d-m-y')}\n";
}

In the example, we create a DatePeriod object that can be iterated through using foreach in the usual way.

Please note that when iterating through such an object, it does not include the last element of the period (it works this way if you used strictly less than in the first example), so we add one day:

$endDate->modify('+1 day')

(Possibly clone is also required here.)

Thus, you can iterate through any period with the desired interval (in our example 'P1D' - 1 day).