This is due to how PHP handles date math. You need to make sure you are always working with the first of the month to ensure February does not get skipped.
DateTime()
, DateInterval()
, and DatePeriod()
makes this really easy to do:
$start = new DateTime('11 months ago');
// So you don't skip February if today is day the 29th, 30th, or 31st
$start->modify('first day of this month');
$end = new DateTime();
$interval = new DateInterval('P1M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format('F Y') . "<br>";
}
You can obviously change $dt->format('F Y')
to $dt->format('M')
to suit your specific purposes. I displayed the month and year to demonstrate how this worked.