# php - create a hole in an array

517

I have an array of the form

``````\$array = array(1 => 'a',
2 => 'b',
3 => 'c',
4 => 'd')
``````

and I would like to create a 'hole' between 2 and 3, i.e. obtain the following array

``````\$array = array(1 => 'a',
2 => 'b',
4 => 'c',
5 => 'd')
``````

What do you reckon to be the best way to do this?

852

#### Solution:

This should work:

``````function array_drill_hole(\$input, \$start, \$end) {
array_splice(\$input, \$start, \$end - \$start, null);
return \$input;
}
``````
930

#### Solution:

``````\$array = array_combine(array_merge(range(1, 2), range(4, 5)), \$array);
``````
884

#### Solution:

``````define("N", 3);

\$i = count(\$array);
while (\$i >= N) {
\$array[\$i+1] = \$array[\$i];
\$i--;
}
unset (\$array[ N ]);
``````

or the equivalent for version

``````define("N", 3);

for(\$i=count(\$array) ; \$i >= N ; \$i--) {
\$array[\$i+1] = \$array[\$i];
}
unset (\$array[ N ]);
``````
894

#### Solution:

``````array_splice(\$array, 2, 0, "");

return array_filter(\$array);
``````
303

#### Solution:

Here is a tested complete solution:

``````function makeHole(\$index,\$holeArr) {
\$returnArr = array();
\$increaseFlag = false;
foreach (\$holeArr as \$ind => \$val) {
if (\$ind == \$index || \$increaseFlag) {
\$increaseFlag = true;
\$returnArr[\$ind+1] = \$val;
} else {
\$returnArr[\$ind] = \$val;
}
}
return \$returnArr;
}

\$array = array(1 => 'a',
2 => 'b',
3 => 'c',
4 => 'd');
\$result = makeHole(3,\$array);
echo '<pre>';
print_r(\$result);
echo '</pre>';
``````
550

#### Solution:

``````\$array = array(1 => 'a',
2 => 'b',
3 => 'c',
4 => 'd');
array_splice(\$array, 2, 0, " ");
array_splice(\$array, 3, 0, " ");
unset(\$array);
unset(\$array);

var_dump(\$array);
``````

Output:

``````array(4) { => string(1) "a" => string(1) "b" => string(1) "c" => string(1) "d" }
``````

People are also looking for solutions to the problem: php - JOIN and COUNT outputting only one result

Source