PHP

Date Range Iterator

admin by @admin ADMIN
Jun 20, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Yield each date in a [start, end] interval as a DateTimeImmutable, with a configurable step. Builds on DatePeriod under the hood — but exposes a generator so you can break out early.
PHP
Raw
<?php
function dateRange(DateTimeInterface $start, DateTimeInterface $end, string $step = 'P1D'): Generator {
    $cursor = DateTimeImmutable::createFromInterface($start);
    $endImm = DateTimeImmutable::createFromInterface($end);
    $stepIv = new DateInterval($step);
    while ($cursor <= $endImm) {
        yield $cursor;
        $cursor = $cursor->add($stepIv);
    }
}

foreach (dateRange(new DateTime('2025-01-01'), new DateTime('2025-01-05')) as $d) {
    echo $d->format('Y-m-d'), PHP_EOL;
}
// 2025-01-01
// 2025-01-02
// 2025-01-03
// 2025-01-04
// 2025-01-05
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.