Created
December 27, 2012 15:04
-
-
Save nathggns/4388952 to your computer and use it in GitHub Desktop.
PHP recursively merge arrays while overwriting non-array values.
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 | |
| /** | |
| * 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