I am creating a function where you can give a starting year, month and end year, month and the function will print every month and year in between the two given points.
I've already created a function that works perfectly but I believe this is not a good practice and there might be better way to do this. Now I am seeking your help to find a better way.
P.S. I can't get full date as input. Only can get month number and year.
Here is my code -
function get_all_months($monthstart = null, $yearstart = null, $monthend = null, $yearend = null) {
if (($monthstart === null) || ($yearstart === null) || ($monthend === null) || ($yearend === null)) {
    $monthend = date('m');
    $yearend = date('Y');
    if($monthend < 6) {
        $yearstart = $yearend - 1;
        $monthstart = (($monthend - 5) + 12);
    } else {
        $yearstart = $yearend;
        $monthstart = $monthend - 5;
    }
}
$month_array = array();
if ($yearstart > $yearend) {
    for ($m=$monthend; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $yearend);
    for ($y=$yearend+1; $y<$yearstart; $y++) for ($m=1; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $y);
    for ($m=1; $m<=$monthstart; $m++) $month_array[] = array('month' => $m, 'year' => $yearstart);
} elseif ($yearend > $yearstart) {
    for ($m=$monthstart; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $yearstart);
    for ($y=$yearstart+1; $y<$yearend; $y++) for ($m=1; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $y);
    for ($m=1; $m<=$monthend; $m++) $month_array[] = array('month' => $m, 'year' => $yearend);
} else {
    for ($m=$monthstart; $m<=$monthend; $m++) $month_array[] = array('month' => $m, 'year' => $yearstart);
}
return $month_array;
}
EDIT: Based on Nigel Ren's answer, this is the best way I could think of -
 function get_all_months($monthstart = null, $yearstart = null, $monthend = null, $yearend = null) {
if (($monthstart === null) || ($yearstart === null) || ($monthend === null) || ($yearend === null)) {
    $monthend = date('m');
    $yearend = date('Y');
    if($monthend < 6) {
        $yearstart = $yearend - 1;
        $monthstart = (($monthend - 5) + 12);
    } else {
        $yearstart = $yearend;
        $monthstart = $monthend - 5;
    }
}
$output = [];
if ($yearstart > $yearend) {
    $time   = strtotime($yearend."-".$monthend);
    $last   = date('m-Y', strtotime($yearstart."-".$monthstart));
} else {
    $time   = strtotime($yearstart."-".$monthstart);
    $last   = date('m-Y', strtotime($yearend."-".$monthend));
}
do {
        $cur_month_year = date('m-Y', $time);
        $month = date('m', $time);
        $year = date('Y', $time);
        $output[] =  array('month'=>$month,'year'=>$year);
        $time = strtotime('+1 month', $time);
    }
    while ($cur_month_year != $last);
    return $output;
}