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?
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.
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.
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" );
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.
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 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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With