Join 2 arrays the easy way in PHP
Today I came across a problem that I do often: I need to join 2 arrays together. My usual friend here is array_merge(). But I decided to use something I had seen a lot in other people's PHP code, but had never tried myself.
I had an array of numbered keys to values and I wanted to prepend a new value without affecting the keys. First I used array_unshift(), but it reset my keys. No good, as they were numerical Ids. Then I turned to array_merge(), which also scrambled my keys.
I decided to use something I have seen in the wild, but never tried myself. That is, to concatenate them using the plus (+) operator.
$joinedArray = $oldArray + $newArray;For those people wondering why it works, apparently it is defined in the interpreter that when using + where all operands are arrays, it does what you may expect... join them all together! I guess it's another random thing a PHP developer should know!
Comments
Andrew Cobby
Posted on Sunday, 21st March 2010 @ 12:21pm.This is ridiculously simple and obvious... And here I was thinking I new everything about PHP.
Great post!
Alexander Dickson
Posted on Saturday, 13th March 2010 @ 9:07am.@Dale J Williams
Yeah, it's an interesting feature. With the adoption of PHP 5.3 by my server, I'll be able to iterate through even less arrays with anonymous functions and array_walk().
Dale J Williams
Posted on Friday, 12th March 2010 @ 8:39pm.I'm surprised that works. I've always used the array_merge() or worse: ran a loop to append both arrays to the new one.
Leave a Comment
Note: Your comment may require approval before it is posted to the site.