Return all dates between two dates in an array in PHP
Given two dates (start date and end date) and the task is to return all the dates in an array.
Example 1: In this example, use date interval class which stores fixed amount of time (in years, months, days, hours etc) or relative time string in the format that DateTime.
[PHP]
function getDatesFromRange($start, $end, $format = ‘Y-m-d’) {
// Declare an empty array
$array = array();
// Variable that store the date interval
// of period 1 day
$interval = new DateInterval(‘P1D’);
$realEnd = new DateTime($end);
$realEnd->add($interval);
$period = new DatePeriod(new DateTime($start), $interval, $realEnd);
// Use loop to store date into array
foreach($period as $date) {
$array[] = $date->format($format);
}
// Return the array elements
return $array;
}
// Function call with passing the start date and end date
$Date = getDatesFromRange(‘2010-10-01’, ‘2010-10-05’);
var_dump($Date);
?>
[/PHP]
OUTPUT array(5) { [0]=> string(10) "2010-10-01" [1]=> string(10) "2010-10-02" [2]=> string(10) "2010-10-03" [3]=> string(10) "2010-10-04" [4]=> string(10) "2010-10-05" }