I'm trying to get an array of 12 months starting with current month, decrement and be like "Mar 2022".
This is my code:
$months = array();
$count = 0;
while ($count <= 11) {
$months[] = date('M Y', strtotime("-".$count." month"));
$count ;
}
But has some problems with months with fewer days.
For example: dd($months[0]) => "Mar 2022"
and dd($months[1]) => "Mar 2022"
had to be "Feb 2022".
CodePudding user response:
One quick solution will as below:
<?php
$months = array();
$count = 0;
while ($count <= 11) {
$prevMonth = ($count == 1) ? "first day of previous month" : "-$count month";
$months[] = date('M Y', strtotime($prevMonth));
$count ;
}
Refrence: Getting last month's date in php
CodePudding user response:
use carbon.
use Carbon\Carbon;
for ($i = 0; $i < 12; $i ) {
array_push($months, Carbon::now()->subMonth($i)->format('M Y'));
};