Skip to content

Instantly share code, notes, and snippets.

@uzyn
Created May 13, 2012 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save uzyn/2688024 to your computer and use it in GitHub Desktop.
Save uzyn/2688024 to your computer and use it in GitHub Desktop.
array_merge recursive
<?php
$a = array(
'asdf' => array(
'qqqq' => 'pppp',
'wwww' => 'oooo',
'eeee' => 'iiii'
),
'default' => 'yes'
);
$b = array(
'asdf' => array(
'qqqq' => 'a',
),
'default' => 'overwriten'
);
print_r(array_merge($a, $b));
print_r(array_merge_recursive($a, $b));
function merge($arr1, $arr2 = null) {
$args = func_get_args();
$r = (array)current($args);
while (($arg = next($args)) !== false) {
foreach ((array)$arg as $key => $val) {
if (!empty($r[$key]) && is_array($r[$key]) && is_array($val)) {
$r[$key] = merge($r[$key], $val);
} elseif (is_int($key)) {
$r[] = $val;
} else {
$r[$key] = $val;
}
}
}
return $r;
}
print_r(merge($a, $b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment