note 32783 deleted from function.array-merge by sniper

From: Date: Mon, 06 Oct 2003 22:54:38 +0000
Subject: note 32783 deleted from function.array-merge by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57915@lists.php.net to get a copy of this message
Note Submitter: cue@openxbox.com ---- 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 :)

« previous php.notes (#57915) next »