Skip to content

Instantly share code, notes, and snippets.

@jehaby
Created May 10, 2016 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehaby/e91b6d35661ba8900644e5d64cc0055b to your computer and use it in GitHub Desktop.
Save jehaby/e91b6d35661ba8900644e5d64cc0055b to your computer and use it in GitHub Desktop.
Enchantment of PHP's array_replace_recursive
<?php
if (!function_exists('array_replace_recursive_overwrite')) {
function array_replace_recursive_overwrite($array, $array1)
{
$recurse = function ($array,$array1) use (&$recurse)
{
foreach ($array1 as $key => $value) {
$overwrite = is_array($value) && empty($value);
// create new key in $array, if it is empty or not an array
if (!isset($array[$key]) || $overwrite || (isset($array[$key]) && !is_array($array[$key]))) {
$array[$key] = array();
}
// overwrite the value in the base array
if (is_array($value)) {
$value = $recurse($array[$key], $value);
}
$array[$key] = $value;
}
return $array;
};
// handle the arguments, merge one by one
$args = func_get_args();
$array = $args[0];
if (!is_array($array)) {
return $array;
}
for ($i = 1; $i < count($args); $i++) {
if (is_array($args[$i])) {
$array = $recurse($array, $args[$i]);
}
}
return $array;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment