Find spaces in a list of numbers

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 in the blanks so that 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, that is, 1,2,3, and then a space, then 10,11,12,13,14, and then a space, and then 23,24,25 .. How can I programmatically find these spaces and add a new array element in its place

There will be a maximum of two spaces.

I can’t think of a good way to do this, any ideas? Thanks.

+6
source share
3 answers

A simple for loop without copying an array, but only changing 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); } } 
+2
source

I would do something like this, not tested, but should work :)

 $oldArray = array(1,2,3,10,11,12,13,24,25,26,27); $newArray = array(); for($i=0;$i<count($oldArray);$i++){ $newArray[] = $oldArray[$i]; if($oldArray[$i+1] - $oldArray[$i] != 1 && $i+1 != count($oldArray)) $newArray[] = "xxx"; // seperator } var_dump($newArray); 

Shay

+1
source
 $result = array(); if (count($oldArray) > 0) { $result[] = $oldArray[0]; for ($i=1; $i<count($oldArray); $i++) { if ($oldArray[$i]-$oldArray[$i-1] != 1) $result[] = "xxx"; $result[] = $oldArray[$i]; } } 
+1
source

Source: https://habr.com/ru/post/900123/


All Articles