Go Premium for a chance to win a PS4. Enter to Win


Looping through Dates in PHP

Posted on 2015-08-14
Medium Priority
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
LVL 14

Assisted Solution

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

Accepted Solution

Julian Hansen earned 1800 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

916 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