简体   繁体   中英

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
)

I think this is just undocumented behaviour, but I'm probably wrong about that. Either way, if you're trying to put arrays together like that, use array_merge

See: http://ca2.php.net/manual/en/function.array-merge.php

When working on arrays, the plus operator doesn't overwrite indexes, nor does it reindex the arrays. In your example c has index 0 just as a , so it's discarded. Use array_merge.

array_splice($a,count($a),0,$b); //array $a becomes a group of $a and $b arrays.

PS它是索引数组(不是关联的)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM