note 32783 added to function.array-merge
| From: | cue at openxbox dot com | Date: | Fri, 06 Jun 2003 18:32:04 +0000 |
| Subject: | note 32783 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-49900@lists.php.net to get a copy of this message | ||
I noticed that array_merge creates a copy of the elements from the original arrays; e.g.:
$a = array('one', 'two', 'three');
$b = array('a', 'b', 'c', 'd');
$c = array_merge($a, $b);
$c[3] = 'four';
If you look at the results of $a, $b, $c after execution, $c[3] is 'four' but the
corresponding element in $b is still 'a'. I found myself in a situation where I wanted to
have a merged array of references to the original arrays, so I wrote a little array_link() method
that served my purpose. It only accepts two arrays and creates a resulting array of only numeric
keys, but feel free to modify it to make it more flexible:
function array_link(&$array1, &$array2)
{
$newarray = array();
foreach($array1 as $key=>$value)
{
$newarray[] = &$array1[$key];
}
foreach($array2 as $key=>$value)
{
$newarray[] = &$array2[$key];
}
return $newarray;
}
Re-running the code with the minor modification:
$a = array('one', 'two', 'three');
$b = array('a', 'b', 'c', 'd');
$c = array_link($a, $b);
$c[3] = 'four';
... shows that now $c[3] is 'four' and $b[0] is 'four' as well. Hope this helps
someone :)
----
Manual Page -- http://www.php.net/manual/en/function.array-merge.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+32783
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+32783&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+32783&report=yes