Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

array_merge is useful – but with a caveat

So, the other day, I saw a horrible thing. I saw two PHP associative arrays that needed to be combined into one, and the worst example of NOT using PHP’s built in functions to combine them. They weren’t using array_merge – instead they were looping through each value.

That’s what I thought until I did some testing. There is a legitimate difference in the looping method vs the array_merge method. This could be by design in your application, so don’t get over-eager optimizing. Lets take a look:

Example Arrays

1
2
$ar1 = array('a'=>'ay', 'b'=>'bee', 'c'=>'see');
$ar2 = array('d'=>'dee', 'e'=>'ee', 'f'=>'ef');

Well, first off, lets try my way – with array_merge:

1
2
$ar2 = array_merge($ar1, $ar2);
var_dump($ar2);
array(6) { ["a"]=>  string(2) "ay" ["b"]=>  string(3) "bee"
["c"]=>  string(3) "see" ["d"]=>  string(3) "dee"
["e"]=>  string(2) "ee" ["f"]=>  string(2) "ef" }

Ok – decent. Now lets try it their way:

1
2
3
4
foreach ($ar1 as $k=>$v) {
    $ar2[$k]=$v;
}
var_dump($ar2);
array(6) { ["d"]=>  string(3) "dee" ["e"]=>  string(2) "ee"
["f"]=>  string(2) "ef" ["a"]=>  string(2) "ay"
["b"]=>  string(3) "bee" ["c"]=>  string(3) "see" }

The array is in a different order.

Special Thanks to Sjan and James for commenting on my original version of this story and explaining that I was totally running in circles!

This entry was posted in PHP and tagged . Bookmark the permalink.

3 Responses to array_merge is useful – but with a caveat

  1. Or, by changing the merge order from

    $ar2 = array_merge($ar1, $ar2);

    to
    $ar2 = array_merge($ar2, $ar1);

    you can come up with the same result.

  2. From the PHP docs:
    “Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. ”

    So, if you want the second array first, why wouldn’t you just do array_merge($ar2, $ar1)?

  3. Aaron says:

    Thanks guys for the comments! What you suggested would also get the desired effect.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>