PHP: Number of consecutive elements in array

algorithm, arrays, php

Solution

$a = [8, 13, 14, 10, 6, 7, 8, 14, 5, 3, 5, 2, 6, 7, 4];

$res = [];
$stage = [];

foreach($a as $i) {
    if(count($stage) > 0 && $i != $stage[count($stage)-1]+1) {
        if(count($stage) > 1) {
            $res[] = $stage;
        }
        $stage = [];
    }
    $stage[] = $i;

}
print_r($res);

Problem

I have been working on one problem: Find the largest group of consecutive numbers in an array. Say we have an array `[5, 43, 4, 56, 3, 2, 44, 57, 58, 1]`, the biggest group of consecutive numbers in this array is 5 (1, 2, 3, 4, and 5). The solution algorithm must be time complexity of O(n). I have solved this with the following ruby code but I am having trouble porting it to PHP as the solution requires. ``` arr = [8, 13, 14, 10, 6, 7, 8, 14, 5, 3, 5, 2, 6, 7, 4] result = [] stage = [] for i in arr: if len(stage) > 0 and i != stage[-1]+1: if len(stage) > 1: result.append(stage) stage = [] stage.append(i) print result ```

Original source