I have number array: 16,17,19,19,20.
I need to find a missing number/gap (in this case it is 18/one number but it may be two numbers e.g.
16,17,20,21) and then i want to fill the gap in a way that rest of the array moves one (x) numbers up.
This array can have more missing numbers (gap) e.g. 16,17,19,19,20,21,23,23.
I have this loop but there is problem – see comment:
<?php
$ar = array(16,17,19,19,20);
$action = false;
$new = array();
$temp = array();
foreach ( $ar as $k => $v ) {
if ( $k == 0 )
{
// case 0 - insert first value of var into array - never need to change
$new[] = $v;
}
elseif ( $k > 0 )
{
if ( end($new) + 1 == $v )
{
// case 1 - numbers are consequence/no gap - insert into array - no change
$new[] = $v;
}
elseif ( end($new) + 1 != $v )
{
// case 2 - there is a gap: find the size of the gap (1,2,x) and then subtract all next values of array with the gap
$gap = $v - end($new) - 1 ; // find value of the gap
//echo "<br> gap is: " . $gap; // PROBLEM - gap get increased by every loop but i need to keep gap size static and process rest of the array
$action = true;
if ( $action = true )
{
$temp[] = $v - $gap;
}
}
}
}
echo "<br>";
print_r ( $new );
echo "<br>";
print_r ( $temp );
so the result is:
array new is ok
Array ( [0] => 16 [1] => 17 )
array temp is not ok
Array ( [0] => 18 [1] => 18 [2] => 18 )
it should be 18,18,19
How is this scenario addressed?
Thanks.
try this, you can make any number of gaps and sequences, and recursion will find the size of gap and shift numbers up, then look for another gap/gaps.