PHP Correctly Get Last 12 Months (Month per Month)

Posted on May 31, 2019 at 9:06 am

PHP snippet to get the last 12 months, month per month:

$dt = new DateTime('first day of this month');
 
for ($i = 1; $i <= 12; $i++) 
{
    echo $dt->format('M Y'), "\n";
 
    $dt->modify('-1 month');
}

Here is an example output of the above PHP code:

May 2019
Apr 2019
Mar 2019
Feb 2019
Jan 2019
Dec 2018
Nov 2018
Oct 2018
Sep 2018
Aug 2018
Jul 2018
Jun 2018

It is important to use ‘first day of this month’, else:

PHP StrToTime() Returns Incorrect Timestamp for ‘-1 MONTH’

Receive updates via email

Other Posts

Updated Posts