Skip to content

Instantly share code, notes, and snippets.

@celosauro
Created August 23, 2019 12:24
Show Gist options
  • Save celosauro/ca4ce75c00f856265b9c2dff4408793f to your computer and use it in GitHub Desktop.
Save celosauro/ca4ce75c00f856265b9c2dff4408793f to your computer and use it in GitHub Desktop.
Grouping sequencial numbers in a subarray
$elements = [1, 2, 3, 4, 6, 7, 10, 15, 20, 21, 22, 33];
$groups = [];
$groupKey = 0;
for ($i = 0; $i < count($elements) ; $i++) {
$currenElement = $elements[$i];
$nextElement = $elements[$i + 1];
$groups[$groupKey][] = $currenElement;
if (($currenElement + 1) != $nextElement) {
$groupKey++;
}
}
print_r($groups);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment