array_push_insert: Push new value into array with PHP

Posted by Gerben Jacobs on May 19, 2011 in tech, php
This blogpost is for historical purposes.
There is a better way with array_splice.

At work today, my colleague needed to add, or rather 'insert', a value into an existing array AND on a specific index. This because we fed it into a JS table sorter, once we pulled it through json_encode().

So what we really required: array_push_insert

We couldn't find any existing Array function at php.net, so I decided to make my own version.

At first I wanted it to work with associative arrays too, but it got complicated fast and at the time we didn't even need it; feature creep. So for now it only works with numeric array keys.

What it does..

First it checks whether the index you supplied ($index) is available in the array ($array), if so, dissects the array in half, starting from the point you supplied ($index) (there's no default function for this either, so I used array_slice). You now have a 'first' and a 'last' array. Then you add your value ($value) to the first array, merge both arrays back together, and you're done!

<?php
function array_push_insert($array, $index, $value) {
    if (array_key_exists($index, $array)) {
        $firstArray = array_slice($array, 0, ($index + 1));
        $lastArray = array_slice($array, ($index + 1));
        array_push($firstArray, $value);
        $array = array_merge($firstArray, $lastArray);
    }
    return $array;
}
?>

Example

We call the function and supply it with our original array, the index after which we want our new value to be inserted and the value itself. So in the next example, we want to add the letter "D" after the "B", and this value's key is 1. So we send in the array ($array), the key (1) and our new value ("D").

<?php
$array = array(
    "A", // 0

    "B", // 1

    "C" // 2

);

$finalArray = array_push_insert($array, 1, "D");
?>

So when we print_r() the $finalArray, it looks like this:

<?php
Array (
    [0] => A
    [1] => B
    [2] => D
    [3] => C
)
?>