phparrayssequentialarray-splicegaps-in-data

Insert an element with a static value into a flat array of ascending integers when there is an increase of more than 1 between values


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.


Solution

  • 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);
        }
    }