Search code examples
phplaraveldatephp-carbon

PHP Carbon Laravel - No 022017


I need to get the last 13 months starting from the current month but when I try the code below. It gets every month but 022017. Any suggestions on why?

for ($i = 13; $i > 0; $i--) {
    $dates->addDate(Carbon::now()->subMonth($i)->format('mY'));
}

results:

0 => "082016"
1 => "092016"
2 => "102016"
3 => "112016"
4 => "122016"
5 => "012017"
6 => "032017"
7 => "042017"
8 => "052017"
9 => "062017"
10 => "072017"
11 => "082017"

Solution

  • Because you use Carbon::now() and you send this question on the 29th. It will skip february because there are only 28 days for that month.

    Something like this should work:

    $now = Carbon::now();
    $month = $now->day = 1;
    for ($i = 13; $i > 0; $i--) {
        $month->subMonth();
        $dates->addDate($month->format('mY'));
    }