PHP: Adding arrays together

Could someone help me explain this? I have two snippets of code, one works as I expect, but the other does not.

This works

$a = array('a' => 1, 'b' => 2);
$b = array('c' => 3);
$c = $a + $b;
print_r($c);

// Output
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

This does not

$a = array('a', 'b');
$b = array('c');
$c = $a + $b;
print_r($c);

// Output
Array
(
    [0] => a
    [1] => b
)

What is going on here?? Why doesn't the second version also add the two arrays together? What have I misunderstood? What should I be doing instead? Or is it a bug in PHP?


This is documented and correct: http://us3.php.net/manual/en/language.operators.array.php

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

So I guess it's not a bug in php and what is suppose happen. I hadn't noticed this before either.


To add two non-associative arrays you need to use the array_merge function:

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.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.


to be short, this works because if you print_r both $a and $b you have:

Array
(
    [a] => 1
    [b] => 2
)

and

Array
(
    [c] => 3
)

as you can see all elements have different keys...

as for the second example arrays, if you print $a and $b you have:

Array
(
    [0] => a
    [1] => b
)

and

Array
(
    [0] => c
)

and that 0 key for both 'a' and 'c' is the issue here, the elements of second array with same keys are discarded... if you do:

$c = $b + $a; // instead of $c = $a + $b;

the result will be:

Array
(
    [0] => c
    [1] => b
)
链接地址: http://www.djcxy.com/p/58952.html

上一篇: 组合数组的PHP

下一篇: PHP:一起添加数组