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 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 the DatePeriod class that has the start date, date interval, and the end date as arguments.

Then we add a foreach loop to loop through the $period and get the dates from $value.

Conclusion

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

Leave a Reply

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