How to run a foreach loop to go through all of those days with PHP?

Spread the love

Sometimes, we want to run a foreach loop to go through all of those days with PHP.

In this article, we’ll look at how to run a foreach loop to go through all of those days with PHP.

How to run a foreach loop to go through all of those days with PHP?

To run a foreach loop to go through all of those days with PHP, we create a DatePeriod object.

For instance, we write

$begin = new DateTime("2022-05-01");
$end = new DateTime("2022-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");
}

to create the $begin and $end DateTime objects.

Then we call DateInterval::createFromDateString to create an $interval object.

Then we create the DatePeriod object with $begin, $interval, and $end that is iterable.

Next, we use the foreach loop to loop through the $period entries which is spaced in the interval of 1 day as specified by $interval.

Conclusion

To run a foreach loop to go through all of those days with PHP, we create a DatePeriod object.

Leave a Reply

Your email address will not be published.