Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find gaps in a list of numbers

Tags:

arrays

php

I have an array like this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 10
    [4] => 11
    [5] => 12
    [6] => 13
    [7] => 14
    [8] => 23
    [9] => 24
    [10] => 25
)

And i want to fill the gaps so it looks like this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => xxx
    [4] => 10
    [5] => 11
    [6] => 12
    [7] => 13
    [8] => 14
    [9] => xxx
    [10] => 23
    [11] => 24
    [12] => 25
)

If you look at the values of the first array there is 1,2,3 and then a gap and then 10,11,12,13,14 and then a gap and then 23,24,25.. How can I programmatically find these gaps and add a new array element in its place

There will be a maximum of two gaps.

I cant think of a good way to do this, any ideas? Thanks.

like image 263
472084 Avatar asked Oct 26 '11 11:10

472084


1 Answers

A simple for loop, without copying the array, but only altering the original:

$repl = 'xxx';

for ($i=1; $i<count($array); $i++) {
    $valueR = $array[$i];
    $valueL = $array[$i-1] === $repl ? $array[$i-2] : $array[$i-1];
    if ($valueR > $valueL + 1) {
        array_splice($array, $i++, 0, $repl);
    }
}
like image 155
netcoder Avatar answered Sep 23 '22 06:09

netcoder