防止价值重叠

I have the following array

array (size=5)
0 => 
array (size=1)
  'margin' => 1
1 => 
array (size=1)
  'margin' => 14
2 => 
array (size=1)
  'margin' => 23
3 => 
array (size=1)
  'margin' => 24
4 => 
array (size=1)
  'margin' => 27

I want to prevent overlapping, I means each one should be at least different by value/interval of 5, and at the same time I don't want the final margin max than 30.

and the margins should only plus/minus around their current values, like the final output can be like below

array (size=5)
0 => 
array (size=1)
  'margin' => 1
1 => 
array (size=1)
  'margin' => 14
2 => 
array (size=1)
  'margin' => 19
3 => 
array (size=1)
  'margin' => 24
4 => 
array (size=1)
  'margin' => 29

So far, I have tried the following code to detect the overlaps

while(list($i, $v) = each($data)) {

    if(!empty($data[$i+1]["margin"])){

        if(($data[$i+1]["margin"]-$v["margin"])<5)
            echo "Overlapping index : ".($i+1).PHP_EOL;

        }
}

but I am having difficulty in doing some algorithm to remove the overlaps in place.

P.S. all the data in array is sorted (margin wise).

Can anybody help me regarding? Thanks in advance.

My suggestion is to recurs through your array:

function f($i)
{
   global $n, $margins;
   // check if index is not out of range 
   if ($i < $n)
   {
        // skip first margin in array   
        if ($i>0)
        {
            // stop if 30 is reached
            if ($margins[$i]['margin'] <= 30)
            {
                // ajust margin if smaller than 5
                if (($margins[$i]['margin'] - $margins[$i-1]['margin']) < 5)
                    $margins[$i]['margin'] = $margins[$i-1]['margin'] + 5;
                // recurs to the next item in the array
                f($i+1);
            }
            else
                unset($margins[$i]);
        }
        else
            f($i+1);
   }
}

// initialize $margin
$margins = array(
            array('margin'=>3),
            array('margin'=>7),
            array('margin'=>15),
            array('margin'=>25),
            array('margin'=>30)
          );    

var_dump($margins); echo "</br>";     

// initialize $n 
$n = count($margins);

// Call recursive function  
f(1);

var_dump($margins); echo "</br>";        

This is because the size of your margins array is small, larger array would use memory resources.