Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last six months list in PHP

Tags:

php

I need the previous six months list and am using the following code for that.

for ($i=6; $i >= 1; $i--) {
  array_push($months, date('M', strtotime('-'.$i.' Month')));
}

print_r($months);

Its gives the wrong output as follows

Array
(
    [0] => 'Dec'
    [1] => 'Dec'
    [2] => 'Jan'
    [3] => 'Mar'
    [4] => 'Mar'
    [5] => 'May'
)

It must be

Array
(
    [0] => 'Nov'
    [1] => 'Dec'
    [2] => 'Jan'
    [3] => 'Feb'
    [4] => 'Mar'
    [5] => 'Apr'
)

Where am i wrong. Help please

like image 539
smk3108 Avatar asked Dec 08 '22 23:12

smk3108


1 Answers

You need to start the calculation from the first day of the month.

$first  = strtotime('first day this month');
$months = array();

for ($i = 6; $i >= 1; $i--) {
  array_push($months, date('M', strtotime("-$i month", $first)));
}

print_r($months);

/*
Array
(
    [0] => Nov
    [1] => Dec
    [2] => Jan
    [3] => Feb
    [4] => Mar
    [5] => Apr
)

*/
like image 186
flowfree Avatar answered Jan 01 '23 09:01

flowfree