I have this
array
(
[0] => 1976,
[1] => 1977,
[2] => 1978,
[3] => 1979,
[4] => 1980,
[5] => 1981,
[6] => 1982,
[7] => 1983,
[8] => 1990,
[9] => 1991,
[10] => 1993,
[11] => 1994,
[12] => 1995
)
And i want to find the interval between gaps so it looks like this:
$tmp[1]= [[0] => 1976, [1] => 1983]
$tmp[1]= [[0] => 1990, [1] => 1991]
$tmp[1]= [[0] => 1993, [1] => 1995]
Eventually I'll be using the same method with largest list of number andy idea ?
Despite the fact that you didn't provide any code, here is something that could work assuming I understood correctly
function getIntervals($array) {
$intervals = [];
$intervalIndex = 0;
for ($i = 0; $i < count($array); $i++) {
//If the beginning is not set, set it.
if (!isset($intervals[$intervalIndex][0])) {
$intervals[$intervalIndex][0] = $array[$i];
}
if ($i != 0) {
if ($array[$i] == ($array[$i - 1] + 1)) {
$intervals[$intervalIndex][1] = $array[$i];
} else {
$intervalIndex++;
$intervals[$intervalIndex][0] = $array[$i];
}
}
}
return $intervals;
}
Here is a usage example with your list:
getIntervals([
1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983,
1990, 1991,
1993, 1994, 1995,
]);
and the expected result:
array:3 [
0 => array:2 [
0 => 1976
1 => 1983
]
1 => array:2 [
0 => 1990
1 => 1991
]
2 => array:2 [
0 => 1993
1 => 1995
]
]