Get the last 12 months in PHP

I'm sure someone has a more elegant solution, but you could start counting backwards from the 1st of this month.

for ($i = 1; $i <= 12; $i++) {
    $months[] = date("Y-m%", strtotime( date( 'Y-m-01' )." -$i months"));
}

It's because not every month has a 31st. So strtotime() is advancing to the next month. i.e. 4/31 = 5/1.

You'd be better off using mktime() for this as it's dumber than strtotime().

UPDATE

To take advantage of a smart function like strtotime() and avoid tracking the year for mktime(), the following is my suggestion:

$month = time();
for ($i = 1; $i <= 12; $i++) {
  $month = strtotime('last month', $month);
  $months[] = date("r", $month);
}
print_r($months);

Adjust logic and optimize as you see fit.


I'd like to propose an alternative solution using DatePeriod instead.

There are a number of caveats to watch out for here. For one, you don't want things like Timezone information, or day/time information to get in your way. You're only interested in the month. So we can normalize some of this information to prevent complications like overflows and daylight savings complications, etc... Since you could easily fall into this trap only on specific dates/times when these rare events occur.

$start = new DateTime;
$start->setDate($start->format('Y'), $start->format('n'), 1); // Normalize the day to 1
$start->setTime(0, 0, 0); // Normalize time to midnight
$start->sub(new DateInterval('P12M'));
$interval = new DateInterval('P1M');
$recurrences = 12;

foreach (new DatePeriod($start, $interval, $recurrences, true) as $date) {
    echo $date->format('F, Y'), "\n"; // attempting to make it more clear to read here
}

Output:

February, 2019
March, 2019
April, 2019
May, 2019
June, 2019
July, 2019
August, 2019
September, 2019
October, 2019
November, 2019
December, 2019
January, 2020

Tags:

Php

Date