16 December 2009

PHP array_insert

I had the need the other day to create an ordered collection object. I wanted to be able to add elements to the end of the collection as well as at any point in the middle of the collection. Since I was using PHP as the language to create this object, an array was the obvious construct to use as the internal implementation for this collection. Adding elements to the end of an array is trivial, but inserting elements into the middle of the array turned out to be a bit more difficult.

My first thought was that PHP has all kinds of array functions so there must be an array_insert function. This assumption turned out to be wrong. My second thought is that I would have to cut the array into two pieces, insert the new element to the end of the first piece and then glue to two arrays back together. In fact, I coded this before reading the documentation for the array_splice function more closely.

The array_splice function has two optional parameters which are very helpful in creating an array_insert function. The first optional parameter is the length option. This option specifies how many elements to remove from the original array starting at the specified offset. The second optional parameter is the replacement option. This parameter specified what to replace the removed elements with. So, in other words, you can tell array_splice to remove 6 elements from an array starting at offset 2 and to replace the 6 elements with what ever is in the replacement array.

This is perfect for mimicking an array_insert function. If you specify to remove 0 elements and pass in the new element as an array of 1 item, it gets inserted at the specified index. Now for the example:
function array_insert($array, $index, $new_element)
{
    return array_splice($array, $index, 0, array($new_element));
}
There you have it, array_insert nice and clean and optimized in c.