1

I want to output the last 13 months, beginning with last month.

my code:

for($i=1;$i<=(13);$i++)
{
   echo date("m",strtotime("-".$i." month"));
}

It worksfine, but today (31.) it looks like this 07 07 05 05 03 03 01 12 12 10 10 08 07

I am missing the months, that do not have 31 days. How can I fix this?

1 Answers1

0

Works with a DateTime object! ;-)

$date = new DateTime('2017-08-31');

for ($i=1; $i<=(13); $i++) {
    $tmpDate = clone $date;
    $tmpDate->modify('last day of -' . $i . ' month');
    echo $tmpDate->format('Y-m-d') . "\n";    
}

The trick is to copy the variable so that you can reduce the months times var $i. Using "last day of -x month" always picks the last day of that month. Reference: https://secure.php.net/manual/en/class.datetime.php

Edwin
  • 1,135
  • 2
  • 16
  • 24