According to the documentation, array_merge() takes two arrays as arguments and returns a merged arrays. Numeric keys are renamed so no data is lost. However, any string keys present in both (or more, as it accepts many arguments) arrays will become the "newer" (second or latter) argument.
This tests how multidimensional arrays are treated.
Merging $array1 :
Array
(
[one] => 101
[two] => Array
(
[inside] => old
[oldonly] => 1
)
)
and $array1 :
Array
(
[one] => 202
[two] => Array
(
[inside] => new
[newonly] => 1
)
)
to produce:
Array
(
[one] => 202
[two] => Array
(
[inside] => new
[newonly] => 1
)
)
Notice how the element $array1['two']['oldonly'] is missing from the result set. That makes sense, because it is not in $array2['two'], and that is what the result's 'two' element has become, but it may not be desireable. In such cases we might consider using array_merge_recursive:
Merge same arrays with array_merge_recursive:
Array
(
[one] => Array
(
[0] => 101
[1] => 202
)
[two] => Array
(
[inside] => Array
(
[0] => old
[1] => new
)
[oldonly] => 1
[newonly] => 1
)
)
However that still may not be the desired result. Notice how the element $array1['two']['inside'] has become an array, as well as 'one'! For this we may want to actually use cake_merge(), called "Set::merge()" in the Cake framework:
<?php
/**
* This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive. The difference
* to the two is that if an array key contains another array then the function behaves recursive (unlike array_merge)
* but does not do if for keys containing strings (unlike array_merge_recursive). See the unit test for more information.
*
* Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
*
* @param array $arr1
* @param array $arr2
* @return array
* @access public
*/
function cake_merge($arr1, $arr2 = null) {
// Get all arguments that were passed to the function
$args = func_get_args();
// If $r has not been set yet
if (!isset($r)) {
// Tpecast the first argument into an array and use it as our resulting $r array
$r = (array)current($args);
}
// Loop through all $args we were given
while(($arg = next($args)) !== false) {
// Loop through all $key / $val pairs of our current $arg
foreach ((array)$arg as $key => $val) {
// If the current $key holds an array and the current $arg and all previous ones ($r)
if (is_array($val) && isset($r[$key]) && is_array($r[$key])) {
// Go for recursive merging
$r[$key] = cake_merge($r[$key], $val);
} elseif (is_int($key)) {
// If it's a numerical index go for auto-incremeting
$r[] = $val;
} else {
// And in case of an associative one do an overwrite
$r[$key] = $val;
}
}
}
// Return the merged array
return $r;
}?>
Merge same arrays with cake_merge:
Array
(
[one] => 202
[two] => Array
(
[inside] => new
[oldonly] => 1
[newonly] => 1
)
)