A concise solution can be written much more elegantly without foreach looping with conditionals.
I'll offer a couple of clean methods leveraging just four array functions calls each.
Input:
$months=[
'Jan' => 'January',
'Feb' => 'February',
'Mar' => 'March',
'Apr' => 'April',
'May' => 'May',
'Jun' => 'June',
'Jul' => 'July',
'Aug' => 'August',
'Sep' => 'September',
'Oct' => 'October',
'Nov' => 'November',
'Dec' => 'December'
];
$range=['Mar','Jun'];
Method #1: (just two lines of code and four functions) Demo
// create indexed array of keys in $month, retain only 2 selected months, get their indexes
$a=array_keys(array_intersect(array_keys($months),$range));
// slice the desired elements using offset and calculated length
var_export(array_slice($months,$a[0],$a[1]-$a[0]+1));
Method #2 (just four lines of code and four functions) Demo
$indexes=array_keys($months); // generate an indexed array of abbreviated months
$start=array_search($range[0],$indexes); // get the index of the starting month
$length=array_search($range[1],$indexes)-$start; // subtract start from end month index
var_export(array_slice($months,$start,$length+1)); // extract the desired elements
Output: (using either method)
array (
'Mar' => 'March',
'Apr' => 'April',
'May' => 'May',
'Jun' => 'June',
)
foreach
in_array()