Looping through Dates in PHP

Posted on 2015-08-14
Last Modified: 2015-08-14
Hi Experts,

How can I loop in between 2 dates?

For example, I have the following code:
//Loop through DR
        $date = new DateTime();
        $date_from = new DateTime($from); //'2015-08-01'
        $date_to = new DateTime($to); //'2015-08'14'
        $date_optput = '';
        $date_compare = '';
        for ($date = $date_from; $date <= $date_to; $date++):
            $date_optput = $date->format('D-M-y');
            echo $date_optput . '<br>';

Open in new window

However, this crashes my browser, ad I'm guessing because it goes through every millisecond? Which is what I don't want.

In comments I added my test data, so I am expecting the following output

Open in new window

Any help will be appreciated.
Question by:APD_Toronto
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 14

Assisted Solution

Dzynit earned 50 total points
ID: 40930498
Maybe someone else could be more helpful, but does this look like what you're trying to do?
LVL 57

Accepted Solution

Julian Hansen earned 450 total points
ID: 40930642
This should do what you want
$from = '2015-07-01';
$to = '2015-07-31';
$dateFrom = new DateTime($from);
$dateTo = new DateTime($to);
$dateInterval = new DateInterval('P1D');
while($dateFrom <= $dateTo) {
	echo $dateFrom->format('Y-m-d') . '<br/>';

Open in new window

Sample here

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question