PHP: How to Insert into an Array CodeUnit 11 DEC 2012

Almost unbelievably so, PHP doesn’t actually feature a neatly named insert into array function (to be fair though, it doesn’t have a neatly named remove from array function either!).

However, inserting values into an array is actually possible, though to do this we need to make use of the array_splice (remove a portion of the array and replace it with something else) function – in a slightly warped way of course.

The more complete manual description: array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] ), with the text: Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.

By leveraging the fact that the function accepts a length input to control just how much of the array gets chopped out, we can in fact insert our new values into an existing array by simply pointing at the required offset in the array where we wish to insert our new values, and make use of a zero length value to ensure that no existing elements get dropped out.

In practice:

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

$input = array("car", "truck", "bus", "train");
array_splice($input, 1, 0, array("motorbike","taxi"));
// $input is now array("car", "motorbike", "taxi", "truck", "bus", "train");


Related Link:

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.