To loop between two dates in PHP, you can use the DateTime class alon…
To loop between two dates in PHP, you can use the DateTime class along with a loop. Here’s an example that demonstrates how to achieve this:
<?php
$startDate = new DateTime('2023-07-01');
$endDate = new DateTime('2023-07-07');
$currentDate = clone $startDate;
while ($currentDate <= $endDate) {
echo $currentDate->format('Y-m-d') . "\n";
$currentDate->add(new DateInterval('P1D')); // Add 1 day to the current date
}
?>
In this example, we have a start date ($startDate) and an end date ($endDate). We create a new instance of the DateTime class for both dates. We also create a variable called $currentDate and set it to the value of $startDate using the clone keyword.
We then enter a while loop that continues until the $currentDate is less than or equal to the $endDate. Inside the loop, we echo the current date using the format method to display it in the desired format.
After printing the current date, we increment the $currentDate by 1 day using the add method and the DateInterval class with the interval specification P1D (which means one day). This ensures that we move to the next date in each iteration of the loop.
By running this code, you will see the dates between the start and end dates printed in the specified format.
Originally published on withnat.com on 4 April 2023. Migrated from WordPress with its original date and URL; the original post had no title, so the heading is taken from its first line.