Using + to merge arrays with PHPUsing + to merge arrays with PHP

Posted October 26th, 2009 in PHP

I've been working at a new job and the interesting thing when working with other people's code is you often learn a heap of stuff you didn't already know. A couple of weeks ago I came across a way to merge arrays in PHP with the + operator, instead of using the array functions (e.g. array_merge) so share this here.

Example

The easiest way to illustrate this is with an example.

Using the plus operator to merge an array really works best with an associative array, otherwise it merges on the numbered indexes, which can lead to some unexpected or odd results.

Here's a couple of arrays, with some intersecting elements and some different elements.

$array1 = array(
    'fruit' => 'apple',
    'vegetable' => 'carrot',
    'drink' => 'water',
    'snack' => 'chips'
);
$array2 = array(
    'fruit' => 'banana',
    'drink' => 'juice',
    'sport' => 'running'
);

The order of precedence with using the + operator to merge these arrays is from left to right. So if we add $array1 and $array2 like so, 'apple' has precendence over 'banana' for the fruit element:

$array3 = $array1 + $array2;

Doing this:

print_r($array3);

results in this:

Array
(
    [fruit] => apple
    [vegetable] => carrot
    [drink] => water
    [snack] => chips
    [sport] => running
)

And the other way around:

$array3 = $array2 + $array1;
print_r($array3);

results in this:

Array
(
    [fruit] => banana
    [drink] => juice
    [sport] => running
    [vegetable] => carrot
    [snack] => chips
)

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus