Skip to content
Advertisement

getting previous 6 months getting issue

I am facing issue to get last 6 months in the basis of month number

    $vBillMonthPrev = '11';

        for ($i = 1; $i < 7; $i++) {
            $m_array[] = date("M-y", mktime(0, 0, 0, $vBillMonthPrev - $i, 15));
        }

foreach ($m_array as $months) {
           echo  $months;
        }

issue is this the above code return Oct-21Sep-21Aug-21Jul-21Jun-21May-21 and required result should be Oct-20 Sep-20 Aug-20 Jul-20 Jun-20 May-20

Advertisement

Answer

One way to deal with your year issue is to compare $vBillMonthPrev with the current month, and if it is greater than that, supplying a year parameter to mktime which is for the previous year. Then you can make a DateTime object from that date, and subtract one month in a loop to generate values into your $m_array. Note that it is preferable to subtract a month at a time rather than making a new date variable, as this will correctly deal with the case where the month underflows into the previous year.

$vBillMonthPrev = '11';
$vBillYearPrev = (int)date('Y') - ((int)$vBillMonthPrev > (int)date('n') ? 1 : 0);

$date = date_create_from_format('U', mktime(0, 0, 0, $vBillMonthPrev, 15, $vBillYearPrev));

$m_array = array();
for ($i = 1; $i < 7; $i++) {
    $date->modify('-1 month');
    $m_array[] = $date->format('M-y');
}

print_r($m_array);

Output:

Array
(
    [0] => Oct-20
    [1] => Sep-20
    [2] => Aug-20
    [3] => Jul-20
    [4] => Jun-20
    [5] => May-20
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement