Created
May 10, 2016 10:06
-
-
Save jehaby/e91b6d35661ba8900644e5d64cc0055b to your computer and use it in GitHub Desktop.
Enchantment of PHP's array_replace_recursive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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