Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I run a DateTime with for or foreach loop to loop through each day and add +3 days to each?

I have 2 dates in PHP, how can I run a for or foreach loop to loop through each day and add +3 days to each?

below I add an example of how I want to get the listing.

  <?php
  $begin = new DateTime( "2022-01-01" );
  $end   = new DateTime( "2022-01-31" );
  for($i=$begin; $i<=$end; $i->modify('+1 day')){    
    for($j=$begin; $j<=$end; $j->modify('+3 day')){
      
      echo $i->format("M d, Y").' => ';
      echo $j->format("M d, Y").'<br/><br/>';
      
      /*  I WANTS TO GET

      * Jan 01, 2022 => Jan 04, 2022
      * Jan 02, 2022 => Jan 05, 2022
      * Jan 03, 2022 => Jan 06, 2022
      *...
      *...
      * Jan 31, 2022 => Feb 03, 2022
      */

    }    
  }    
?>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If the end date is always simply three days from the start, then you only need one loop, over the start date. Then, instead of a second loop to set the ending date, just set it relative to the start, on each iteration:

for ($start = $begin; $start <= $end; $start->modify('+1 day')) {    
    $stop = clone $start;
    $stop->modify('+3 days');
    printf("%s => %s\n", $start->format("M d, Y"), $stop->format("M d, Y"));
}

Note you need to make a new date object via clone so that your second modification of +3 days doesn’t change the start date.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading