I have 2 dates in PHP, how can I run a foreach loop to go through all of those days ?

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days ?

Asked on December 13, 2018 in PHP.
Add Comment


  • 3 Answer(s)

    Try the below elucidation,

    $begin = new DateTime('2010-05-01');
    $end = new DateTime('2010-05-10');
     
    $interval = DateInterval::createFromDateString('1 day');
    $period = new DatePeriod($begin, $interval, $end);
     
    foreach ($period as $dt) {
        echo $dt->format("l Y-m-d H:i:s\n");
    }
    

    The indicated output every days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. Have a look at PHP Manual for DatePeriod.

    Answered on December 13, 2018.
    Add Comment

    Use this code to get the solution, you have to include the final date.

    $begin = new DateTime( "2015-07-03" );
    $end = new DateTime( "2015-07-09" );
    for($i = $begin; $i <= $end; $i->modify('+1 day')){
        echo $i->format("Y-m-d");
    }
    

    In some cases, we never want the last date just remove = from the condition.

    Answered on December 13, 2018.
    Add Comment

    Try to use this code:

    Actually the novice to unix timestamps makes doing date math should very simple in php, like this:

    $startTime = strtotime( '2010-05-01 12:00' );
    $endTime = strtotime( '2010-05-10 12:00' );
     
    // Loop between timestamps, 24 hours at a time
    for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
      $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
    }
    

    If we using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping.

    Answered on December 13, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.