0

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".

Ivar
  • 6,138
  • 12
  • 49
  • 61
  • I recommend you to use the `Carbon` library that is automatically included if you are using Laravel. This makes DateTime mutations so much easier to handle. – Aless55 Mar 30 '22 at 07:19

2 Answers2

1

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

Rikesh
  • 26,156
  • 14
  • 79
  • 87
0

use carbon.

    use Carbon\Carbon;
     

 
     for ($i = 0; $i < 12; $i++) {
        array_push($months, Carbon::now()->subMonth($i)->format('M Y'));
    };
yadu siva das
  • 517
  • 3
  • 12