Generate consecutive years ranges from array of years in PHP
I have array:
'years' =>
array (size=28)
0 => string '1985'
1 => string '1986'
2 => string '1987'
3 => string '1988'
4 => string '1989'
5 => string '1990'
6 => string '1991'
7 => string '1992'
8 => string '1993'
9 => string '1994'
10 => string '1996'
11 => string '1997'
12 => string '1998'
13 => string '1999'
14 => string '2000'
15 => string '2001'
16 => string '2002'
17 => string '2005'
18 => string '2008'
19 => string '2011'
20 => string '2012'
21 => string '2013'
22 => string '2014'
23 => string '2015'
24 => string '2016'
25 => string '2017'
26 => string '2019'
27 => string '2020'
What is the fastest way to generate ranges of consecutive years from this array? My goal is to accomplish exactly this array:
array(
0 => '1985-1994',
1 => '1996-2002',
2 => '2005',
3 => '2008',
4 => '2011-2017',
5 => '2019-2020'
);
Years 2005 and 2008 don't have consecutive years, so are inserted alone. Array list of years would vary ofcourse.
Answer
Solution:
If someone would need a solution to such a problem, there is a ready code below.
$range_started = 0;
$ranges = [];
$last_year = end($years);
foreach($years as $year) {
if (!$range_started) {
$range_started = $year;
$next_expected = $year+1;
continue;
}
if ($year == $next_expected) {
$next_expected++;
if ($year < $last_year)
continue;
}
$ne = $next_expected-1;
if ($range_started < $ne)
$ranges[] = $range_started . '-' . $ne;
else
$ranges[] = $range_started;
$range_started = $year;
$next_expected = $year+1;
}
Source