Created
July 13, 2012 11:39
-
-
Save mattsah/3104455 to your computer and use it in GitHub Desktop.
A non-recursive version 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 | |
/** | |
* Many examples of pre 5.3 versions of this function use recursion | |
* this one avoids it for people who, like me, are only going to rely | |
* on this logic in a single place. In short, you can fully remove the | |
* function definition and implications and the actual code will still | |
* work. That is, the function does not need to call itself. | |
*/ | |
function array_replace_recursive($base, $replacements) | |
{ | |
foreach (array_slice(func_get_args(), 1) as $replacements) { | |
$bref_stack = array(&$base); | |
$head_stack = array($replacements); | |
do { | |
end($bref_stack); | |
$bref = &$bref_stack[key($bref_stack)]; | |
$head = array_pop($head_stack); | |
unset($bref_stack[key($bref_stack)]); | |
foreach (array_keys($head) as $key) { | |
if (isset($bref[$key]) && is_array($bref[$key]) && is_array($head[$key])) { | |
$bref_stack[] = &$bref[$key]; | |
$head_stack[] = $head[$key]; | |
} else { | |
$bref[$key] = $head[$key]; | |
} | |
} | |
} while(count($head_stack)); | |
} | |
return $base; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment