Take the following list:
445
446
661
662
1978
1979
2014
2015
2016
2017
2018
2019
2020
2021
2021
2022
2673
2674
What is the best approach to sort this list so you end up with a result that groups all the number ranges found in the list chronologically?
E.g, wanted result would be 5 arrays:
[445, 446]
[661, 662]
[1978, 1979]
[2014 ... 2022]
[2673, 2674]
Try this:
$array = array(
445,446,661,662,1978,1979,2014,2015,2016,2017,2018,2019,2020,2021,
2021,2022,2673,2674
);
$result = array();
$tmp = array();
for ($i = 0; $i < count($array); $i++) {
if (array_key_exists($i + 1, $array) && ($array[$i + 1]) - $array[$i] == 1) {
$tmp[] = $array[$i];
} else {
$tmp[] = $array[$i];
$result[] = $tmp;
$tmp = array();
}
}
var_dump($result);
Output:
array
0 =>
array
0 => int 445
1 => int 446
1 =>
array
0 => int 661
1 => int 662
2 =>
array
0 => int 1978
1 => int 1979
3 =>
array
0 => int 2014
1 => int 2015
2 => int 2016
3 => int 2017
4 => int 2018
5 => int 2019
6 => int 2020
7 => int 2021
4 =>
array
0 => int 2021
1 => int 2022
5 =>
array
0 => int 2673
1 => int 2674
NOTE:
There are two 2021 value in your array. Maybe you can use array_unique
to get only the unique values.