note 104771 modified in function.array-merge by danbrown

From: Date: Wed, 06 Jul 2011 14:45:26 +0000
Subject: note 104771 modified in function.array-merge by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181293@lists.php.net to get a copy of this message
I'm sorry, but I've not found on this page a function that would properly merge two arrays while overwriting numeric values. Considering two arrays: <?php $test1 = array(array('a','b','c'), 'a', 'b'); $test2 = array(array('d','e'), 'c'); ?> while using overwrite merge you would expect the result to be an array: <?php $test3 = array(array('d','e'), 'c', 'b'); ?> However most of the functions will result with this array: <?php $test4 = array(array('d','e','c'), 'c', 'b'); ?> So, here's a function to do that: <?php function array_merge_overwrite(array &$array1, array $array2 = NULL) { $flag = true; foreach (array_keys($array2) as $key) { if (isset($array2[$key]) && is_array($array2[$key])) { if (isset($array1[$key]) && is_array($array1[$key])) array_merge_overwrite($array1[$key], $array2[$key]); else $array1[$key] = $array2[$key]; $flag = false; } } if ($flag == true) $array1 = $array2; } ?> --was-- I'm sorry, but I've not found on this page a function that would properly merge two arrays while overwriting numeric values. Considering two arrays: $test1 = array(array('a','b','c'), 'a', 'b'); $test2 = array(array('d','e'), 'c'); while using overwrite merge you would expect the result to be an array: $test3 = array(array('d','e'), 'c', 'b'); However most of the functions will result with this array: $test4 = array(array('d','e','c'), 'c', 'b'); So, here's a function to do that: function array_merge_overwrite(array &$array1, array $array2 = NULL) { $flag = true; foreach (array_keys($array2) as $key) { if (isset($array2[$key]) && is_array($array2[$key])) { if (isset($array1[$key]) && is_array($array1[$key])) array_merge_overwrite($array1[$key], $array2[$key]); else $array1[$key] = $array2[$key]; $flag = false; } } if ($flag == true) $array1 = $array2; } http://php.net/manual/en/function.array-merge.php

« previous php.notes (#181293) next »