I do not understand where I made a mistake, I want to display the months for the year, but starting from the old ones. writing:

$datestart = date("mY",strtotime("-1 years")); for($mm = 1; $mm < 12; $mm++): $month = date($datestart, strtotime('+$mm month')); $month.'<br>'; endfor; 

but in the end, $month remains equal to $datestart

  • one
    What does "starting with the old" mean? Old ... what!? - rjhdby

2 answers 2

And, on the other hand, DateInterval can be used for this task:

 $dateTime = new DateTime('-1 year'); $month = new DateInterval('P1M'); do { $dateTime->add($month); echo $dateTime->format('Y-m') . PHP_EOL; } while($dateTime < new DateTime()); 

Or even more beautiful with DatePeriod :

 $datePeriod = new DatePeriod(new DateTime('-1 year'), new DateInterval('P1M'), new DateTime('now')); foreach ($datePeriod as $date) { echo $date->format('Y-m') . PHP_EOL; } 

The truth is that the current month is lost in this version, you have to play a little.

    If you take into account only your code, then there are at least two errors:

    strtotime ('+ $ mm month'))

    For a variable to be interpreted as a variable, double quotes are needed instead of single quotes.

    $ month = date ($ datestart, strtotime ('+ $ mm month'));

    In the date function, the first parameter is to pass the date format, not the date itself.

    Those. in the end, fix one line:

     $month = date('Y-m', strtotime("+$mm month"));