How to return all dates between two dates in an array with PHP?

Spread the love

Sometimes, we want to return all dates between two dates in an array with PHP.

In this article, we’ll look at how to return all dates between two dates in an array with PHP.

How to return all dates between two dates in an array with PHP?

To return all dates between two dates in an array with PHP, we can use the DatePeriod class.

For instance, we write

$period = new DatePeriod(
     new DateTime('2022-10-01'),
     new DateInterval('P1D'),
     new DateTime('2022-10-05')
);

foreach ($period as $key => $value) {
    //...
}

to create a DatePeriod object with the start DateTime, DateInterval and DateTime.

'P1D' means the interval between dates is 1 day.

Then we can iterate through the dates with a foreach loop.

Conclusion

To return all dates between two dates in an array with PHP, we can use the DatePeriod class.

Leave a Reply

Your email address will not be published. Required fields are marked *