note 41394 modified in function.array-merge by vrana

From: Date: Tue, 17 Aug 2004 13:58:43 +0000
Subject: note 41394 modified in function.array-merge by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80064@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): <?php 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; } ?> --was-- 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; } http://php.net/manual/en/function.array-merge.php

« previous php.notes (#80064) next »