Question

Say you have a 10 element indexed array and you want to place an element somewhere in the middle (say index 3). Then I want to have the rest of the array shift and thus be 11 elements long. Is there an easy way to do this?

I am surprised there is no put() function or something.

I know it would be easy enough to do this with a combination of array_splice and array_merge but I was just wondering if there an easier way.

Was it helpful?

Solution

array_splice() does this

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green", "blue", "purple", "yellow");

OTHER TIPS

Unfortunately your best bet is what you described in your post.

If you use array_splice(), PHP will still have to copy half the array to do the insert, which will be a performance hit for large array sizes. Maybe you should be using a list or tree datastructure instead?

The only time I've ever needed to insert into the middle of an array was when I was doing some operation that's substantially similar to insertion sort. Maybe you want to store the items unsorted in an array, and then sort them once you've added them all?

No PHP function can currently handle this. It is not too difficult to whip up your own, however:

function array_insert(&$array, $insert, $position) {
    $c = count($array);
    $slice = array_merge($insert, array_slice($array, $position));
    array_splice($array, $position, $c, $slice);
}

$array = array('a','b','d','e');
print_r($array);
array_insert($array, array('c'), 2);
print_r($array);

Will result in:

Array
(
    [0] => a
    [1] => b
    [2] => d
    [3] => e
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)

You can probably add checks if the position is bigger than the array, the insert is not an array, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top