This should do it:
function combine_months($months) { $all_months = array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); $target = array(); $start = null; for ($i = 0; $i<12; $i++) { if (!in_array($all_months[$i], $months) && $start != null) { if ($start == null) { $target[] = $all_months[$i-1]; } else { $target[] = sprintf("%s - %s", $start, $all_months[$i-1]); } $start = null; } elseif ($start == null) { $start = $all_months[$i]; } } if ($start != null) { $target[] = $start; } return $target; } $test = combine_months(array("Jan","Feb","Mar","Apr","May","Jun","Sep","Oct","Dec")); var_dump($test);
Iterates over all available months, recalling the first common month, adding to the target array when there is not enough month.
source share