note 41394 added to function.array-merge
| From: | mail at nospam dot iaindooley dot com | Date: | Thu, 08 Apr 2004 13:37:52 +0000 |
| Subject: | note 41394 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-67820@lists.php.net to get a copy of this message | ||
hey there, here is a nice little way of merging two arrays that may or may not have numerical or
string indices and preserving the order and indexing of both arrays whilst making the most use of in
built php functions (i actually originally wanted to use array_combine for obvious reasons but
seeing as that is not available in PHP4, the little foreach loop at the end is necessary):
function merge($arr1,$arr2)
{
if(!is_array($arr1))
$arr1 = array();
if(!is_array($arr2))
$arr2 = array();
$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);
$keys = array_merge($keys1,$keys2);
$vals1 = array_values($arr1);
$vals2 = array_values($arr2);
$vals = array_merge($vals1,$vals2);
$ret = array();
foreach($keys as $key)
{
list($unused,$val) = each($vals);
$ret[$key] = $val;
}
return $ret;
}
----
Manual Page -- http://www.php.net/manual/en/function.array-merge.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41394
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41394&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41394&report=yes
Search -- http://master.php.net/manage/user-notes.php