PHP: get last 6 months in format month year
Have you tried following:
<?php
echo date('F, Y');
for ($i = 1; $i < 6; $i++) {
echo date(', F Y', strtotime("-$i month"));
}
Let me know, if this wont work.
Do not use:
<?php
for ($i = 0; $i <= 6; $i++) {
echo date('F Y', strtotime(-$i . 'month'));
}
// With date e.g.: "May, 31", outputs:
// May, 2018, May 2018, March 2018, March 2018, January 2018, December 2017
You can fix it by:
<?php
for ($i = 0; $i <= 6; $i++) {
echo date('F Y', strtotime('last day of ' . -$i . 'month'));
}
Or better use DateTime, e.g.:
$dateTime = new DateTime('first day of this month');
for ($i = 1; $i <= 6; $i++) {
echo $dateTime->format('F Y');
$dateTime->modify('-1 month');
}
Try this
for ($j = 0; $j <= 5; $j++) {
echo date("F Y", strtotime(" -$j month"));
}