- preg_match: documentation ( source)
- print_r: documentation ( source)
- date: documentation ( source)
- strtotime: documentation ( source)
<?php
$start_date = '2014-01-01';
$end_date = '2015-01-31';
$date_regex = "/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/";
if (!empty($start_date) & !empty($end_date) && preg_match($date_regex, $start_date) && preg_match($date_regex, $end_date)) {
$start = new \DateTime($start_date);
$end = new \DateTime($end_date);
$now = new \DateTime();
$intervals = [];
while ($start <= $end) {
$first_day = $start->format('Y-m-d');
if ( $start->format('Y-m') === $now->format('Y-m') ) {
$last_day = $now->format('Y-m-d');
} else {
$last_day = date('Y-m-t', strtotime($start->format('Y-m')));
}
$intervals[ $first_day ] = $last_day;
$start->modify('first day of next month');
}
echo '<pre>';print_r($intervals);
}