0

I'm testing some code of PHP(5.4.4) in apache(2.2.22).

I wonder how PHP actually work in parsing the code below.

<?php

$x = array(
    'st1' => 'gd1',
    'st2' => 'gd2'
);

$y = array(
    'st1' => 'te1',
    'st3' => 'te3'
);

$z = $x + $y;
var_dump($z);

The result is

array(3) { ["st1"]=> string(3) "gd1" ["st2"]=> string(3) "gd2" ["st3"]=> string(3) "te3" } 

But how it works?

eg(I guessed): $x first parsed and added into $z, while parsing $y, the php interpreter think the key 'st1' existed(means $x's priority is higher than $y), and tried not to override it and add 'st3' and it's value.

Just want to make sure whether I misunderstood it...

3
  • The ever-helpful PHP docs tell you execatly what is happening.... it's the union of $x and $y Commented Jul 27, 2014 at 12:34
  • 1
    Link above, this fragment: "The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored. " Commented Jul 27, 2014 at 12:34
  • Sorry you all, I must be out of my mind while reading the drupal source... Commented Jul 27, 2014 at 12:54

3 Answers 3

1

PHP merges those arrays based on the key type. If the keys are numeric, all value will appear in the new array. If the keys are strings, duplicates will overwrite earlier occurrences.

See also: array_merge — Merge one or more arrays

Sign up to request clarification or add additional context in comments.

Comments

1

In case of using the concatenate operator, it only adds up new array-keys into the first array. So essentially, the first array is untouched and new keys from the second array is added.

If you want to override the first array with the second try this:

$x = array(
    'st1' => 'gd1',
    'st2' => 'gd2'
);

$y = array(
    'st1' => 'te1',
    'st3' => 'te3'
);

$z = array_merge($x,$y);
var_dump($z);

In this case, if both arrays have the same index, the latter overwrites the former. Any number of arrays can be passed for merging.

Comments

1

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

So, basically if you're going left to right you'll only add key/value where the key does already exists.

Hope this help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.