Skip to content

Instantly share code, notes, and snippets.

@nathggns
Created December 27, 2012 15:04
Show Gist options
  • Select an option

  • Save nathggns/4388952 to your computer and use it in GitHub Desktop.

Select an option

Save nathggns/4388952 to your computer and use it in GitHub Desktop.
PHP recursively merge arrays while overwriting non-array values.
<?php
/**
* Recursively merge arrays, overwriting non-array values.
*
* @param array $first First array
* @param array $second Second array
* ...
*/
function array_merge_recursive_overwrite() {
// Get all of our arguments
$args = func_get_args();
// Make sure we have arguments to work with
if (count($args) < 2) return;
// Handle more than 2 arrays
if (count($args) > 2) {
while (count($args) > 2) {
$first = array_shift($args);
$second = array_shift($args);
array_unshift($args, array_merge_recursive_overwrite($first, $second));
}
$args = array_merge_recursive_overwrite($args[0], $args[1]);
return $args;
}
$first = $args[0];
$second = $args[1];
foreach ($second as $key => $val) {
if (isset($first[$key]) && is_array($first[$key])) {
$val = array_merge_recursive_overwrite($first[$key], $val);
}
$first[$key] = $val;
}
return $first;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment