How to return array of all dates between two dates in PHP? In some cases you will need a feature like this, especially when working with charts! Luckily this is very easy task for PHP.
To return all dates in a given date range, we can use two methods, native PHP solution and using Carbon library.
1. Using PHP native solution
You can achieve this by using PHP DateInterval class :
<?php
$range = new DatePeriod(
new DateTime('2020-12-01'),
new DateInterval('P1D'), // date range 1 day
new DateTime('2020-12-10')
);
$date_array = [];
foreach ($range as $key => $value) {
array_push($date_array, $value->format('Y-m-d'));
}
print_r($date_array);
// output:
Array
(
[0] => 2020-12-01
[1] => 2020-12-02
[2] => 2020-12-03
[3] => 2020-12-04
[4] => 2020-12-05
[5] => 2020-12-06
[6] => 2020-12-07
[7] => 2020-12-08
[8] => 2020-12-09
)
As you can see we are using interval of 1 day: new DateInterval('P1D') , and if we change this to for example P2D - we will get every second date
<?php
$range = new DatePeriod(
new DateTime('2020-12-01'),
new DateInterval('P2D'), // date range 2 days
new DateTime('2020-12-10')
);
$date_array = [];
foreach ($range as $key => $value) {
array_push($date_array, $value->format('Y-m-d'));
}
print_r($date_array);
// output:
Array
(
[0] => 2020-12-01
[1] => 2020-12-03
[2] => 2020-12-05
[3] => 2020-12-07
[4] => 2020-12-09
)
date interval has many more options, you can get range in seconds, weeks, months... check it out here.
2. Using Carbon library
Carbon is much more powerful PHP library, and it is used as built in library for Dates in Laravel.
So, how to generate all dates in a date range using Carbon (and Laravel)?
<?php
use Carbon\CarbonPeriod;
$start = '2020-12-01';
$end = '2020-12-10';
$period = CarbonPeriod::create($start, $end);
$date_array = [];
foreach ($period as $dateKey => $dateValue) {
array_push($date_array, $value->format('Y-m-d'));
}
print_r($date_array);
// output:
Array
(
[0] => 2020-12-01
[1] => 2020-12-02
[2] => 2020-12-03
[3] => 2020-12-04
[4] => 2020-12-05
[5] => 2020-12-06
[6] => 2020-12-07
[7] => 2020-12-08
[8] => 2020-12-09
)
To read more about CarbonPeriod you can visit this link: https://carbon.nesbot.com/docs/#api-period.