As an adaptation of this answer of mine, use a lookup array and references to push consecutive month names into the correct element -- use strtok()
and concatenation to ensure that the end of range is always updated correctly.
This snippet will perform well because it only uses one loop and there are no in_array()
calls (one of PHP's slows forms of searching an array).
Code: (Demo)
$lookup = array_flip(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']);
$months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Sep', 'Oct', 'Dec'];
$result = [];
foreach ($months as $month) {
if (isset($ref) && $lookup[$month] === $lookup[$last] + 1) {
$ref = strtok($ref, "-") . "-$month";
} else {
unset($ref);
$ref = $month;
$result[] = &$ref;
}
$last = $month;
}
var_export($result);
Or written differently to leverage $i
instead of $last
because the input array is indexed. (Demo)
$result = [];
foreach ($months as $i => $month) {
if ($i && $lookup[$month] === $lookup[$months[$i - 1]] + 1) {
$ref = strtok($ref, "-") . "-$month";
} else {
unset($ref);
$ref = $month;
$result[] = &$ref;
}
}
var_export($result);
If your input array needs to accommodate circular referencing, use the modulus operator with 12 (the number of months in a year) to ensure that Jan "looks back" to Dec. (Demo)
if (isset($ref) && $lookup[$month] === ($lookup[$last] + 1) % 12) {