How to Loop Between Two Dates in PHP

Last Updated May 28, 2023 by . First Published in 2010.

How to Loop Between Two Dates in PHP

In programming languages its easy to loop between two numbers or run a foreach over items in array, but what about a loop between two dates?

The problem was simple enough, I wanted to loop over all the days between two dates, taking a new month or year into account and rolling over automatically.

Luckily there is a way loop between two dates in PHP which is actually pretty simple and uses a while loop.

php
date_default_timezone_set('UTC');

$start_date = '2010-01-01';
$end_date = '2010-03-15';

while (strtotime($start_date) <= strtotime($end_date)) {
    echo "$start_daten";
    $start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
}

You can adjust to +1 days to +2 days for every other day, or +1 week for every week between two dates.

Was this article helpful to you?
 
Comments

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.