Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Adding arrays together

Tags:

arrays

php

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?

like image 866
Svish Avatar asked May 11 '10 15:05

Svish


People also ask

How can I merge two arrays in PHP?

The array_merge() function merges one or more arrays into one array. Tip: You can assign one array to the function, or as many as you like. Note: If two or more array elements have the same key, the last one overrides the others.

How do I combine two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How can I append an array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );

What happens when you add arrays together?

In summary, the addition of arrays causes them to be coerced into strings, which does that by joining the elements of the arrays in a comma-separated string and then string-concatenating the joined strings.


2 Answers

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.

like image 135
jdcantrell Avatar answered Sep 21 '22 10:09

jdcantrell


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 ) 
like image 43
acm Avatar answered Sep 19 '22 10:09

acm