• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 484
  • Last Modified:

Looping through Dates in PHP

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>';
        endfor;

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
1-Aug-15
2-Aug-15
3-Aug-15
4-Aug-15
...
14-Aug-15
15-Aug-15

Open in new window


Any help will be appreciated.
0
APD Toronto
Asked:
APD Toronto
2 Solutions
 
DzynitCommented:
Maybe someone else could be more helpful, but does this look like what you're trying to do?
http://www.if-not-true-then-false.com/2009/php-loop-through-dates-from-date-to-date-with-strtotime-function/
0
 
Julian HansenCommented:
This should do what you want
<?php
$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/>';
	$dateFrom->add($dateInterval);
}

Open in new window

Sample here
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now