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
*/
}
}
?>
>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.