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…
$a = array("a" => "Cat","b"=>"Dog"); array_unshift($a,"Horse"); print_r($a);The output of the code above will be:
This one works only if you want the key of the first element to be 0. In my example, 0 was there by accident.
Yes you got it right,, keeping it simple is the key. in our programming class we were told that any coder can write code but a super code is that which is precise and simple!