note 89684 added to function.array-merge-recursive
| From: | daniel at danielsmedegaardbuus dot dk | Date: | Thu, 19 Mar 2009 10:18:21 +0000 |
| Subject: | note 89684 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-152126@lists.php.net to get a copy of this message | ||
<?php
/**
* array_merge_recursive does indeed merge arrays, but it converts values with duplicate
* keys to arrays rather than overwriting the value in the first array with the duplicate
* value in the second array, as array_merge does. I.e., with array_merge_recursive,
* this happens (documented behavior):
*
* array_merge_recursive(array('key' => 'org value'), array('key'
=> 'new value'));
* => array('key' => array('org value', 'new value'));
*
* array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
* Matching keys' values in the second array overwrite those in the first array, as is the
* case with array_merge, i.e.:
*
* array_merge_recursive_distinct(array('key' => 'org value'),
array('key' => 'new value'));
* => array('key' => array('new value'));
*
* Parameters are passed by reference, though only for performance reasons. They're not
* altered by this function.
*
* @param array $array1
* @param mixed $array2
* @return array
* @author daniel@danielsmedegaardbuus.dk
*/
function &array_merge_recursive_distinct(array &$array1, &$array2 = null)
{
$merged = $array1;
if (is_array($array2))
foreach ($array2 as $key => $val)
if (is_array($array2[$key]))
$merged[$key] = is_array($merged[$key]) ? array_merge_recursive_distinct($merged[$key],
$array2[$key]) : $array2[$key];
else
$merged[$key] = $val;
return $merged;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 62.243.22.18
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/89684
Del: integrated -- https://master.php.net/note/delete/89684/integrated
Del: useless -- https://master.php.net/note/delete/89684/useless
Del: bad code -- https://master.php.net/note/delete/89684/bad+code
Del: spam -- https://master.php.net/note/delete/89684/spam
Del: non-english -- https://master.php.net/note/delete/89684/non-english
Del: in docs -- https://master.php.net/note/delete/89684/in+docs
Del: other reasons-- https://master.php.net/note/delete/89684
Reject -- https://master.php.net/note/reject/89684
Search -- https://master.php.net/manage/user-notes.php