Search code examples
phplaraveldatephp-carbon

How to get month name of custom range


In my laravel application, The input is like this:

$from_year = 2019;
$from_month = 10;

$to_year = 2020;
$to_month = 4;

The expected output:

months = [
'October 2019', 'November 2019', 'December 2019', 'January 2020', 'February 2020', 'March 2020', 'April 2020'
]

Thanks in advance.


Solution

  • $startDate = date($from_year.'-'.$from_month.'-01');
    $diff = (($to_year - $from_year) * 12) + ($to_month - $from_month);
    
    $months = [];
    for($i=0;$i<=$diff;$i++) {
        $months[] = date('F Y', strtotime('+'.$i.' month', strtotime($startDate)));
    }
    

    simple code with date() function