Last week, while programming, I needed to insert an array at the beginning of another. So, since basically I was just merging 2 arrays, I tried to do it like this:

$originalArray = array(
    1 => 'First item',
    4 => 'Forth item',
    5 => 'Fift item',
    10 => 'Tenth item', // and so on
);

$insertAtBegining = array(
    0 => 'None',
);

$newArray = array_merge($insertAtBegining, $originalArray);

But it didn’t work. :( It was displaying something like:

Array
(
    [0] => None
    [1] => First item
    [2] => Forth item
    [3] => Fifth item
    [4] => Tenth item
)

Not a good result, because the arrays’ keys were actually primary keys used by the RDBMS so it was very important for me to keep the original keys. I didn’t want to take the lame approach and do a foreach loop:

$newArray = $insertAtBegining;
foreach($originalArray as $key => $value) {
    $newArray[$key] = $value;
}

…because it was too obvious, so I did something less obvious, and much more complicated:

$newArray = array_combine(
    array_merge(array_keys($insertAtBegining), array_keys($originalArray)),
    array_merge(array_values($insertAtBegining), array_values($originalArray))
);

But in the end, Chris, one of my colleagues who also has a blog at SegmentationFault.es pointed out the most simple and elegant solution:

$newArray = $insertAtBegining + $originalArray;

This reminds me of the saying “Keep It Simple Stupid” :) Which Chris uses as a wallpaper…