PHP: Return all dates between two dates in an array
You could also take a look at the DatePeriod class:
$period = new DatePeriod(
new DateTime('2010-10-01'),
new DateInterval('P1D'),
new DateTime('2010-10-05')
);
Which should get you an array with DateTime objects.
To iterate
foreach ($period as $key => $value) {
//$value->format('Y-m-d')
}
This is very very flexible.
/**
* Creating date collection between two dates
*
* <code>
* <?php
* # Example 1
* date_range("2014-01-01", "2014-01-20", "+1 day", "m/d/Y");
*
* # Example 2. you can use even time
* date_range("01:00:00", "23:00:00", "+1 hour", "H:i:s");
* </code>
*
* @author Ali OYGUR <[email protected]>
* @param string since any date, time or datetime format
* @param string until any date, time or datetime format
* @param string step
* @param string date of output format
* @return array
*/
function date_range($first, $last, $step = '+1 day', $output_format = 'd/m/Y' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange = [];
$iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
$iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
if ($iDateTo >= $iDateFrom) {
array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
while ($iDateFrom<$iDateTo) {
$iDateFrom += 86400; // add 24 hours
array_push($aryRange, date('Y-m-d', $iDateFrom));
}
}
return $aryRange;
}
source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html