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

Answer

Solution:

This should work:

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

Answer

Solution:

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

Answer

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

Answer

Solution:

I want to join: http://codepad.org/9JDGHxhK

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

return array_filter($array);
303

Answer

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

Answer

Solution:

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

var_dump($array);

Output:

array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [4]=> string(1) "c" [5]=> string(1) "d" } 

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

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.