Ever needed to loop over every day between 2 dates for a data set you need? From time to time I do and this can come in handy especially when making graphs or charts for example. Luckily, it's super easy to do this with some date & time extensions.

Let's say you want to loop over every day between 2 specific dates, we can achieve this result with this code:

$startDate = new DateTime('2016-03-15');
$endDate = new DateTime('2016-05-01');

// These are the steps in which we will be iterating
$interval = DateInterval::createFromDateString('1 day');

// Create the period between the start/end  date and the interval
$period = new DatePeriod($startDate, $interval, $endDate);

// Loop over the period
foreach ($period as $dateTime) {
    // A certain day in this period
    $date = $dateTime->format('Y-m-d');

We can also do this with relative times by changing the start date and end date. For example, the last 30 days:

$startDate = new DateTime('now - 30 days');
$endDate = new DateTime('now');

Obviously there's many ways to get around this, this is one way to quickly achieve this using PHP only.

Cheers! 🍻

Post comment