probably simpler versions of this (below) but thought i'd post my solution up as it might be helpful :)
<?php
function array_merge_php4_comp() {
$n=func_num_args();
if( $n>0 ) {
$rval=func_get_arg(0);
if( !is_array($rval) ) {
$rval=(array)$rval;
}
if( $n>1 ) {
for( $i=1; $i<$n; $i++ ) {
$tval=func_get_arg($i);
if( !is_array($tval) ) {
$tval=(array)$tval;
}
$rval=array_merge($rval, $tval);
}
} else {
$rval=array_merge($rval);
}
} else {
$rval=array_merge();
}
return $rval;
}
?>
array_merge
(PHP 4, PHP 5)
array_merge — Führt ein oder mehrere Arrays zusammen
Beschreibung
array_merge() fügt die Elemente von einem oder mehreren Arrays zusammen, indem die Werte des einen an das Ende des anderen angehängt werden. Das daraus resultierende Array wird zurückgegeben.
Haben die angegebenen Arrays die selben String-Schlüssel, dann wird der hintere Wert dieses Schlüssels den vorhergehenden überschreiben. Haben die Arrays den gleichen numerischen Schlüssel, dann wird der hintere Wert den vorhergehenden nicht überschreiben, sondern angehängt.
Falls nur ein Array angegeben und dieses numerisch indiziert ist, wird das Array fortlaufend neu nummeriert.
Beispiel #1 array_merge()
<?php
$array1 = array("farbe" => "rot", 2, 4);
$array2 = array("a", "b", "farbe" => "grün", "form" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
Nun ist $result:
Array ( [farbe] => grün [0] => 2 [1] => 4 [2] => a [3] => b [form] => trapezoid [4] => 4 )
Beispiel #2 Einfaches array_merge() Beispiel
<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>
Vergessen Sie nicht, dass numerische Schlüssel neu numeriert werden!
Array ( [0] => data )
Wenn Sie die Arrays komplett erhalten und nur eines an das andere anhängen wollen, verwenden Sie den Operator +:
<?php
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
?>
Der numerische Schlüssel sowie die Assoziation bleiben erhalten.
Array ( [1] => data )
Das Verhalten von array_merge() wurde in PHP 5 geändert. Anders als in PHP 4 akzeptiert array_merge() jetzt nur noch Parameter vom Typ array. Man kann jedoch Typumwandlung verwenden, um andere Typen zusammenzuführen. Schauen Sie für Details in das Beispiel unten.
Beispiel #3 array_merge() PHP 5 Beispiel
<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array ( [0] => foo [1] => bar )
Siehe auch array_merge_recursive(), array_combine() und array operators.
array_merge
08-May-2008 06:19
29-Apr-2008 04:51
I needed a function to interlace two arrays ([a,b,c] + [d,e,f] = [a,d,b,e,c,f]) and came up with the following. This function works for arrays of varying lengths and keeps the keys sequenced properly.
<?php
$a = array ('a', 'b', 'c');
$b = array ('d', 'e', 'f', 'g', 'h', 'i');
$c = array_interlace ($a, $b);
/*
Array
(
[0] => a
[1] => d
[2] => b
[3] => e
[4] => c
[5] => f
[6] => g
[7] => h
[8] => i
)
*/
function array_interlace ($a, $b)
{
$c = array();
$shorty = (count($a) > count($b)) ? $b : $a;
$biggy = (count($a) > count($b)) ? $a : $b;
$slen = count($shorty);
$blen = count($biggy);
for ($i = 0; $i < $slen; ++$i){
$c[$i * 2] = $a[$i];
$c[$i * 2 + 1] = $b[$i];
}
for ($i = $slen; $i < $blen; ++$i)
{
$c[] = $biggy[$i];
}
return $c;
}
?>
04-Apr-2008 03:02
The documentation is a touch misleading when it says: "If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way." Even with two arrays, the resulting array is re-indexed:
[bishop@predator staging]$ cat array_merge.php
<?php
$a = array (23 => 'Hello', '42' => 'World');
$a = array_merge(array (0 => 'I say, '), $a);
var_dump($a);
?>
[bishop@predator staging]$ php-5.2.5 array_merge.php
array(3) {
[0]=>
string(7) "I say, "
[1]=>
string(5) "Hello"
[2]=>
string(5) "World"
}
[bishop@predator staging]$ php-4.4.7 array_merge.php
array(3) {
[0]=>
string(7) "I say, "
[1]=>
string(5) "Hello"
[2]=>
string(5) "World"
}
03-Apr-2008 07:30
@Kevin Campbell:
Yep, be carefull....the docu is misleading....
$beginning = 'foo';
$end = array(0 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
will produce:
Array
(
[0] => foo
[1] => bar
)
whereas the `+` operator:
$beginning = 'foo';
$end = array(0 => 'bar');
$result = (array)$beginning + (array)$end;
print_r($result);
will produce:
Array
(
[0] => foo
)
03-Mar-2008 08:31
PHP is wonderfully decides if an array key could be a number, it is a number! And thus wipes out the key when you array merge. Just a warning.
$array1['4000'] = 'Grade 1 Widgets';
$array1['4000a'] = 'Grade A Widgets';
$array2['5830'] = 'Grade 1 Thing-a-jigs';
$array2['HW39393'] = 'Some other widget';
var_dump($array1);
var_dump($array2);
//results in...
array(2) {
[4000]=>
string(15) "Grade 1 Widgets"
["4000a"]=>
string(15) "Grade A Widgets"
}
array(2) {
[5830]=>
string(20) "Grade 1 Thing-a-jigs"
["HW39393"]=>
string(17) "Some other widget"
}
var_dump(array_merge($array1,$array2));
//results in...
array(4) {
[0]=>
string(15) "Grade 1 Widgets"
["4000a"]=>
string(15) "Grade A Widgets"
[1]=>
string(20) "Grade 1 Thing-a-jigs"
["HW39393"]=>
string(17) "Some other widget"
}
04-Nov-2007 12:38
As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.
18-Oct-2007 07:45
Re: Renumbering arrays:
This (from rcarvalhoREMOVECAPS at clix dot pt):
$a = array_merge($a, null);
does not renumber the array in PHP5. However this:
$a = array_merge($a, array());
does renumber the $a array in PHP5.
I think that's more clear than the other renumbering proposal, though I don't know about performance:
$b = implode(" ", $a);
$a = explode(" ", $b);
Hope this helps...
16-Aug-2007 03:33
The notes in Example 257 above are incorrect. It states:
If you want to completely preserve the arrays and just want to append them to each other, use the + operator
Check the array type page at http://www.php.net/manual/en/language.types.array.php which states differently. Duplicate keys are ignored with the + operator.
21-Jul-2007 04:52
Similar to Jo I had a problem merging arrays (thanks for that Jo you kicked me out of my debugging slumber) - array_merge does NOT act like array_push, as I had anticipated
<?php
$array = array('1', 'hello');
array_push($array, 'world');
var_dump($array);
// gives '1', 'hello', 'world'
$array = array('1', 'hello');
array_merge($array, array('world'));
// gives '1', 'hello'
$array = array('1', 'hello');
$array = array_merge($array, array('world'));
// gives '1', 'hello', 'world'
?>
hope this helps someone
26-Jun-2007 04:14
in regards to Joe's problem with arr1 + arr2 versus array_merge(arr1, arr2) - this seems to have been fixed in php 5.2.3
$arr1['foo'] = 'bar';
$arr2['bar'] = 'baz';
$arr3 = $arr1 +$arr2;
print_r($arr3) will produce:
array(
'foo' => 'bar',
'bar' => 'baz'
);
I should also note that array_merge() will convert strings of integers into integers for php 5.2.3. For example:
$arr1['007'] = 'james bond';
$arr2['008'] = 'some other spy';
$arr3 = array_merge($arr1, $arr2);
print_r($arr3) will produce:
array(
7 => 'james bond',
8 => 'some other spy'
);
so if you must maintain leading zeros, it's best to use $arr1 + $arr2 instead of array_merge.
03-Jun-2007 11:51
I found the "simple" method of adding arrays behaves differently as described in the documentation in PHP v5.2.0-10.
$array1 + $array2 will only combine entries for keys that don't already exist.
Take the following example:
$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = ($ar1 + $ar2);
print_r($ar3);
Result:
Array
(
[0] => a
[1] => b
)
Where as:
$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = array_merge($ar1, $ar2);
print_r($ar3);
Result:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
Hope this helps someone.
21-May-2007 05:05
For asteddy at tin dot it and others who are trying to merge arrays and keep the keys, don't forget the simple + operator.
Using the array_merge_keys() function (with a small mod to deal with multiple arguments), provides no difference in output as compared to +.
<?php
$a = array(-1 => 'minus 1');
$b = array(0 => 'nought');
$c = array(0 => 'nought');
var_export(array_merge_keys($a,$b));
var_export($a + $b);
var_export(array_merge_keys($a,$b,$c));
var_export($a + $b + $c);
?>
results in ...
array ( -1 => 'minus 1', 0 => 'nought',)
array ( -1 => 'minus 1', 0 => 'nought',)
array ( -1 => 'minus 1', 0 => 'nought',)
array ( -1 => 'minus 1', 0 => 'nought',)
02-Mar-2007 04:21
I have been searching for an in-place merge function, but couldn't find one. This function merges two arrays, but leaves the order untouched.
Here it is for all others that want it:
function inplacemerge($a, $b) {
$result = array();
$i = $j = 0;
if (count($a)==0) { return $b; }
if (count($b)==0) { return $a; }
while($i < count($a) && $j < count($b)){
if ($a[$i] <= $b[$j]) {
$result[] = $a[$i];
if ($a[$i]==$b[$j]) { $j++; }
$i++;
} else {
$result[] = $b[$j];
$j++;
}
}
while ($i<count($a)){
$result[] = $a[$i];
$i++;
}
while ($j<count($b)){
$result[] = $b[$j];
$j++;
}
return $result;
}
24-Jan-2007 06:06
An earlier comment mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
21-Jan-2007 10:23
I recently upgrade from PHP4 to PHP5. While using PHP4, there was a certain set of information that we filtered into the $_SESSION global at login. i.e.
$_SESSION = array_merge( $_SESSION, $additional_vals );
This method worked great in PHP4, but not in PHP5. I can only assume the session immediately invalidated itself.
In fact, my tests to find this bug, led me to find out that all session changes - even those before this action - were lost.
DO NOT USE array_merge() FROM $_SESSION AND TO $_SESSION
16-Jan-2007 07:51
Sorry, I forgot to translate the the name of the function when it calls itself. Here is the correct code:
<?
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
foreach($arr2 as $k=>$v) {
if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
$arr1[$k]=$v;
}
else { // K EXISTS //
if (is_array($v)) { // K IS AN ARRAY //
$arr1[$k]=array_merge_keys($arr1[$k], $arr2[$k]);
}
}
}
return $arr1;
}
?>
15-Jan-2007 06:06
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
foreach($arr2 as $k=>$v) {
if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
$arr1[$k]=$v;
}
else { // K EXISTS //
if (is_array($v)) { // K IS AN ARRAY //
$arr1[$k]=array_unisci_chiavi($arr1[$k], $arr2[$k]);
}
}
}
return $arr1;
}
13-Dec-2006 10:47
To: zspencer at zacharyspencer dot com
You forget about code of this function.
<?
function safe_array_merge($a, $b) {
foreach ($b as $v) {
$a[] = $v;
}
return $a;
}
?>
09-Nov-2006 08:55
I noticed the lack of a function that will safely merge two arrays without losing data due to duplicate keys but different values.
So I wrote a quicky that would offset duplicate keys and thus preserve their data. of course, this does somewhat mess up association...
<?php
$array1=array('cats'=>'Murder the beasties!', 'ninjas'=>'Use Ninjas to murder cats!');
$array2=array('cats'=>'Cats are fluffy! Hooray for Cats!', 'ninjas'=>'Ninas are mean cat brutalizers!!!');
$array3=safe_array_merge($array1, $array2);
print_r($array3)
A more efficient array_merge that preserves keys, truly accepts an arbitrary number of arguments, and saves space on the stack (non recursive):
<?php
function array_merge_keys(){
$args = func_get_args();
$result = array();
foreach($args as &$array){
foreach($array as $key=>&$value){
$result[$key] = $value;
}
}
return $result;
}
?>
28-Sep-2006 07:10
Needed an quick array_merge clone that preserves the keys:
<?
// function array_join
// merges 2 arrays preserving the keys,
// even if they are numeric (unlike array_merge)
// if 2 keys are identical, the last one overwites
// the existing one, just like array_merge
// merges up to 10 arrays, minimum 2.
function array_join($a1, $a2, $a3=null, $a4=null, $a5=null, $a6=null, $a7=null, $a8=null, $a9=null, $a10=null) {
$a=array();
foreach($a1 as $key=>$value) $a[$key]=$value;
foreach($a2 as $key=>$value) $a[$key]=$value;
if (is_array($a3)) $a=array_join($a,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$a10);
return $a;
}
?>
12-Sep-2006 05:45
You can use array_slice() in combination with array_merge() to insert values into an array like this:
<?php
$test=range(0, 10);
$index=2;
$data="---here---";
$result=array_merge(array_slice($test, 0, $index), array($data), array_slice($test, $index));
var_dump($result);
?>
04-Sep-2006 01:34
array_merge() overwrites ALL numerical indexes. No matter if you have non-numerical indexes or more than just one array.
It reindexes them all. Period.
(Only tried in 4.3.10)
Whoops!!! The 2nd posting before this one about the array_merge_alternative1() I made. Replace part of that code with this one below...
--snip--
/* 07/20/2006 - Added the if statement to avoid the warning message spitted out by array_unique() function, "Warning: Wrong datatype in array_unique() call"... */
if ($xyz != 0) {
$new_array2 = array_unique($new_array1); /* Work a lot like DISTINCT() in SQL... */
} else {
$new_array2 = array();
}
--snip--
Because the unique_array() unexpectly give a warning message when it's empty... Sorry about that...
20-Jul-2006 06:02
I don't think that the comment on + operator for array in array_merge page, was understandable, this is just a little test to know exactly what's happend.
<?php
//test code for (array)+(array) operator
$a1 = array( '10', '11' , '12' , 'a' => '1a', 'b' => '1b');
$a2 = array( '20', '21' , '22' , 'a' => '2a', 'c' => '2c');
$a = $a1 + $a2;
print_r( $a );
//result: Array ( [0] => 10
// [1] => 11
// [2] => 12
// [a] => 1a
// [b] => 1b
// [c] => 2c )
$a = $a2 + $a1;
print_r( $a );
//result: Array ( [0] => 20
// [1] => 21
// [2] => 22
// [a] => 2a
// [c] => 2c
// [b] => 1b )
?>
19-Jul-2006 09:28
I found that array_merge() didn't work in my case as it should have because I still get duplicate values. Again, I noticed that the values can be overwritten if the array's key are the same as stated in the manual.
So, I came up with the alternative and it work like a charm.
--snip--
function array_merge_alternative1() {
//echo func_num_args(); /* Get the total # of arguements (parameter) that was passed to this function... */
//print_r(func_get_arg()); /* Get the value that was passed in via arguement/parameter #... in int, double, etc... (I think)... */
//print_r(func_get_args()); /* Get the value that was passed in via arguement/parameter #... in arrays (I think)... */
$loop_count1 = func_num_args();
$junk_array1 = func_get_args();
$xyz = 0;
for($x=0;$x<$loop_count1;$x++) {
$array_count1 = count($junk_array1[$x]);
if ($array_count1 != 0) {
for($y=0;$y<$array_count1;$y++) {
$new_array1[$xyz] = $junk_array1[$x][$y];
$xyz++;
}
}
}
$new_array2 = array_unique($new_array1); /* Work a lot like DISTINCT() in SQL... */
return $new_array2;
}
--snip--
Cheer...
12-Jul-2006 05:36
Do not use this to set the $_SESSION variable.
$_SESSION = array_merge( $_SESSION, $another_array );
will break your $_SESSION until the end of the execution of that page.
18-May-2006 08:32
I needed a function to alternatly merge 2 arrays. i.e. $a1 = (a, c, e) and $a2 = (b, d, f), and now $merged = (a, b, c, d, e, f).
Hope it helps...
<?
function alternatly_merge_arrays($array1, $array2){
$combined_array = array();
$count = 0;
for($i = 0; $i < count($array1) + count($array2); $i = $i + 2){
$combined_array[$i] = $array1[$count];
$count++;
}//end for
$count = 0;
for($i = 1; $i < count($array1) + count($array2); $i = $i + 2){
$combined_array[$i] = $array2[$count];
$count++;
}//end for
return $combined_array;
}//end alternate_merge_arrays
?>
16-Jan-2006 01:22
I forgot to comment. This function join two arrays adding first the elements equals in the two arrays, then the values of the first array and at the end the values of the second array.
<?php
function array_merge_sim ($arr1, $arr2) {
$i=0;
$adid_arrayS = array();
foreach ($arr1 as $x) {
$j=0;
$nr1=count($arr1);
$nr2=count($arr2);
foreach ($arr2 as $z) {
if($x==$z){
array_push($adid_arrayS,$z);
if($nr2==($j+1)) array_pop($arr2);
else array_splice($arr2, $j,-($nr2-$j-1));
if($nr1==($i+1)) array_pop($arr1);
else array_splice($arr1, $i,-($nr1-$i-1));
$i--;
}else $j++;
}
$i++;
}
return array_merge($adid_arrayS,$arr1,$arr2);
}
?>
04-Jan-2006 01:18
Since my comment from 12-Jul-2004 02:42 with <? function array_merge_php4() ?> was deleted and the complex one added by Barpfotenbaer (09-Jul-2005 06:33), - here is the simpler and faster solution:
<?
/* works only with PHP 5 */
function array_merge_php4($array1, $array2) {
foreach ($args = func_get_args() as &$arg) {
$arg = (array)$arg;
}
return call_user_func_array('array_merge',$args);
}
?>
29-Dec-2005 02:50
The same result as produced by snookiex_at_gmail_dot_com's function
can be achieved with the 'one-liner'
<?php
$array1=array(1,2,3);
$array2=array('a','b','c');
$matrix = array_map(null, $array1, $array2);
?>
(see documentation of array_map).
The difference here is, that the shorter array gets filled with empty values.
10-Dec-2005 06:09
if you have, for instance:
$array1=array(1,2,3);
$array2=array('a','b','c');
but you want a 2x3 matrix like this:
1 a
2 b
3 c
use:
function arrays2matrix($array1,$array2){
if(sizeof($array1) != sizeof($array2))
return;
for($i=0;$i<sizeof($array1);$i++)
$res[]=array_merge($array1[$i],$array2[$i]);
return $res;
}
17-Nov-2005 02:17
I was in need of a version of array_merge to add associative arrays without losing duplicate keys. I use the following function:
[code]
function array_add( $array1, $array2 )
{
foreach( $array2 AS $key => $value )
{
while( array_key_exists( $key, $array1 ) )
$key .= "_";
$array1[ $key ] = $value;
}
return $array1;
}
[/code]
In my case the $key is a date I want to sort on, and if I happen to have duplicate dates (users add things on the same timestamp) I lose that entry with array_merge. I can sort on the key without getting big missorts because of the appended '_'.
02-Nov-2005 03:56
If you need to merge two arrays without having multiple entries, try this:
<?php
function array_fusion($ArrayOne, $ArrayTwo)
{
return array_unique(array_merge($ArrayOne, $ArrayTwo));
}
?>
07-Oct-2005 04:25
<?
/*
Warning: if one variable is not an array, the merged array will
have one more line!
*/
$a = "";
$b[0] = "Brazil";
$b[1] = "China";
$c = array_merge($a, $b);
print_r($c);
?>
This returns:
Array
(
[0] =>
[1] => Brazil
[2] => China
)
__________________________________
Rafael Pereira dos Santos
31-Aug-2005 11:55
I wanted to share this, it's an small simple script to add things into an array using an loop/routine.
I use an more developed version to sort msessage's on a forum.
<?php
// Make vars ready
$a=0;
$alltopic = array();
// Start an routine
// 4 is just an example you can use an varible containing
// the number of rows in an databse for example
while ($a < 4)
{
$topic = array($a => "$a");
$alltopic = array_merge ($alltopic, $topic);
$a++;
};
// Put it on screen:
print_r($alltopic);
?>
outputs this :
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
20-Jul-2005 04:58
<?php
/*
* array_deep_merge
*
* array array_deep_merge ( array array1 [, array array2 [, array ...]] )
*
* Like array_merge
*
* array_deep_merge() merges the elements of one or more arrays together so
* that the values of one are appended to the end of the previous one. It
* returns the resulting array.
* If the input arrays have the same string keys, then the later value for
* that key will overwrite the previous one. If, however, the arrays contain
* numeric keys, the later value will not overwrite the original value, but
* will be appended.
* If only one array is given and the array is numerically indexed, the keys
* get reindexed in a continuous way.
*
* Different from array_merge
* If string keys have arrays for values, these arrays will merge recursively.
*/
function array_deep_merge()
{
switch( func_num_args() )
{
case 0 : return false; break;
case 1 : return func_get_arg(0); break;
case 2 :
$args = func_get_args();
$args[2] = array();
if( is_array($args[0]) and is_array($args[1]) )
{
foreach( array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key )
if( is_string($key) and is_array($args[0][$key]) and is_array($args[1][$key]) )
$args[2][$key] = array_deep_merge( $args[0][$key], $args[1][$key] );
elseif( is_string($key) and isset($args[0][$key]) and isset($args[1][$key]) )
$args[2][$key] = $args[1][$key];
elseif( is_integer($key) and isset($args[0][$key]) and isset($args[1][$key]) ) {
$args[2][] = $args[0][$key]; $args[2][] = $args[1][$key]; }
elseif( is_integer($key) and isset($args[0][$key]) )
$args[2][] = $args[0][$key];
elseif( is_integer($key) and isset($args[1][$key]) )
$args[2][] = $args[1][$key];
elseif( ! isset($args[1][$key]) )
$args[2][$key] = $args[0][$key];
elseif( ! isset($args[0][$key]) )
$args[2][$key] = $args[1][$key];
return $args[2];
}
else return $args[1]; break;
default :
$args = func_get_args();
$args[1] = array_deep_merge( $args[0], $args[1] );
array_shift( $args );
return call_user_func_array( 'array_deep_merge', $args );
break;
}
}
/*
* test
*/
$a = array(
0,
array( 0 ),
'integer' => 123,
'integer456_merge_with_integer444' => 456,
'integer789_merge_with_array777' => 789,
'array' => array( "string1", "string2" ),
'array45_merge_with_array6789' => array( "string4", "string5" ),
'arraykeyabc_merge_with_arraykeycd' => array( 'a' => "a", 'b' => "b", 'c' => "c" ),
'array0_merge_with_integer3' => array( 0 ),
'multiple_merge' => array( 1 ),
);
$b = array(
'integer456_merge_with_integer444' => 444,
'integer789_merge_with_array777' => array( 7,7,7 ),
'array45_merge_with_array6789' => array( "string6", "string7", "string8", "string9" ),
'arraykeyabc_merge_with_arraykeycd' => array( 'c' => "ccc", 'd' => "ddd" ),
'array0_merge_with_integer3' => 3,
'multiple_merge' => array( 2 ),
);
$c = array(
'multiple_merge' => array( 3 ),
);
echo "<pre>".htmlentities(print_r( array_deep_merge( $a, $b, $c ), true))."</pre>";
?>
14-Jul-2005 06:44
Old behavior of array_merge can be restored by simple variable type casting like this
array_merge((array)$foo,(array)$bar);
works good in php 5.1.0 Beta 1, not tested in other versions
seems that empty or not set variables are casted to empty arrays
09-Jul-2005 09:33
Topic: The modified behavior of array_merge() in PHP5: "array_merge() now only accepts parameters of type array"
A very simple way to simulate the old behavior of PHP4 to merge arrays with non-arrays:
<?php
function array_merge_php4 ()
{
$array["merged"]=array ();
for($i=0;$i<func_num_args ();$i++)
{
$array["tmp"]=(
(is_array (func_get_arg ($i)))?
(func_get_arg ($i)):
(array (func_get_arg ($i)))
);
$array["merged"]=array_merge ($array["merged"],$array["tmp"]);
}
return($array["merged"]);
}
?>
08-Jul-2005 11:37
About the behavior of array_merge() that was modified in PHP5. The above warning says "array_merge() now only accepts parameters of type array". But it doesn't say what happens when array_merge() is given a non array parameter like in:
<?php
error_reporting(E_STRICT);
$a = array("red","green");
$rgb = array_merge($a,"blue");
?>
In fact, the PHP5 version of array_merge() will perfectly accept the "blue" parameter and will return... the NULL value! Be aware that you will get no warning even with the error reporting level set to E_STRICT (which is supposed to catch "forward compatibility" troubles).
06-Jul-2005 10:56
As "rcarvalhoREMOVECAPS at clix dot pt" suggested above,
$a = array_merge($a, null);
does renumber the $a array. However, this only works with PHP4, not with PHP5. PHP5 users might try the following:
$b = implode(" ", $a);
$a = explode(" ", $b);
Hope this helps someone too ;-)
24-May-2005 09:02
To insert an array inside another at a given position
<?php
//Insert at $pos array $items inside array $source
function array_insert($source, $pos, $items)
{
$sub1 = array_slice($source, 0, $pos);
$sub2 = array_slice($source, $pos);
return array_merge($sub1,$items,$sub2);
}
// 2nd alternative (Note: it changes $source)
function array_insert($source, $pos, $items)
{
$rest = array_splice($source, $pos);
return $source = array_merge($source,$items,$rest);
}
?>
19-Apr-2005 04:54
Here are a few functions to make a diff between two arrays (or 2 strings, see the example) and merge it back after
<?
function array_diff_both($new,$old)
{
$del=array_diff_assoc($old,$new);
$add=array_diff_assoc($new,$old);
return $diff=array("del"=>$del, "add"=>$add);
}
function array_diff_all($arr_new,$arr_old)
{
$arr_equ=array_intersect_assoc($arr_new,$arr_old);
$arr_del=array_diff_assoc($arr_old,$arr_new);
$arr_add=array_diff_assoc($arr_new,$arr_old);
return $diff=array("equ"=>$arr_equ, "del"=>$arr_del, "add"=>$arr_add);
}
function array_merge_diff($arr,$diff) {
$arr=array_merge_replace($arr,$diff["del"]);
$arr=array_merge_replace($arr,$diff["add"]);
return $arr;
}
function array_merge_diff_reverse($arr,$diff) {
$arr=array_merge_replace($arr,$diff["add"]);
$arr=array_merge_replace($arr,$diff["del"]);
return $arr;
}
?>
Here is an example:
<?
//calculationg
$new="hello!"; // new string
$old="hrllo!"; // old string with a typo fault
// cast string in array the goodway
// make a cast (array) to a string does not work:
// the entire string is thus considered as one element
// of the array !!
$a_new=str_split($new);
$a_old=str_split($old); // cast string in array
$diff=array_diff_both($a_new,$a_old); // the entire diff
$test=array_merge_diff($a_old,$diff);
$test_reverse=array_merge_diff_reverse($a_new,$diff);
//for output the sample
print "new= $new<br/>old= $old<br/>\$a_new= ";
print_r($a_new);
print "<br/>\$a_old= ";
print_r($a_old);
print "<br/>\$diff=\$a_new-\$a_old";
print "<br/>\$diff= ";
print_r($diff);
print "<br/>\$test=\$a_old+\$diff";
print "<br/>\$test= ";
print_r($test);
print("<br/>".implode($test));
print "<br/>\$test_reverse=\$a_new+\$diff";
print "<br/>\$test_reverse= ";
print_r($test_reverse);
print("<br/>".implode($test_reverse));
?>
En sortie de l'exemple, résultats:
new= hello!
old= hrllo!
$a_new= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
$a_old= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [1] => r ) [add] => Array ( [1] => e ) )
$test=$a_old+$diff
$test= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
hello!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
hrllo!
autre exemple, autre résultat:
new= see you!
old= sea ya!
$a_new= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
$a_old= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [2] => a [5] => a [6] => ! ) [add] => Array ( [2] => e [5] => o [6] => u [7] => ! ) )
$test=$a_old+$diff
$test= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
see you!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! [7] => ! )
sea ya!!
14-Apr-2005 09:32
The following function merges two arrays taking as parameter an user-defined comparison function:
<?
function array_merge_custom(&$array1,&$array2,$comparison_func)
{
$ret_arr = array();
foreach ($array1 as $key1 => $element1)
{
$has_equal_in_2 = false;
foreach($array2 as $key2 => $element2)
{
if (call_user_func($comparison_func,$element1,$element2))
{
$has_equal_in_2 = true;
}
}
if (!$has_equal_in_2)
{
$ret_arr[] = $array1[$key1];
}
}
$ret_arr = array_merge($ret_arr,$array2);
return $ret_arr;
}
?>
For instance:
<?
$a = array(
array('index' => 'ball', 'blabla' => 0),
array('index' => 'coconut'),
array('index' => 'cow'),
array('index' => 'son'),
);
$b = array(
array('index' => 'phone'),
array('index' => 'wallet'),
array('index' => 'ball'),
array('index' => 'son', 'kabum'=> 1)
);
$c = array_merge_custom($a,$b,create_function('$a,$b','return $a[\'index\'] == $b[\'index\'];'));
print_r($c)
?>
Will produce:
Array
(
[0] => Array
(
[index] => coconut
)
[1] => Array
(
[index] => cow
)
[2] => Array
(
[index] => phone
)
[3] => Array
(
[index] => wallet
)
[4] => Array
(
[index] => ball
)
[5] => Array
(
[index] => son
[kabum] => 1
)
)
06-Apr-2005 01:17
Note that casting the array doesn't always work. For classes, it looks like the class information is lost. The print_r's below have different behavior. I would suggest creating an array, rather than casting in most situations. (ie. do it like $array2).
class myclass {
private $name;
private $value;
function myclass($n, $v) {
$this->name=$n;
$this->value=$v;
}
}
$itema = new myclass("hair", "orange");
$itemb = new myclass("eyes", "green");
$itemc = new myclass("elbow", "dirty");
$items = array($itemb, $itemc);
print "<BR>";
$array1 = array_merge((array)$itema, $items);
$array2 = array_merge(array($itema), $items);
print "<BR>";
print "<BR>";
print_r($array1);
print "<BR>";
print "<BR>";
print_r($array2);
Array ( [] => orange [0] => myclass Object ( [name:private] => eyes [value:private] => green ) [1] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )
Array ( [0] => myclass Object ( [name:private] => hair [value:private] => orange ) [1] => myclass Object ( [name:private] => eyes [value:private] => green ) [2] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )
20-Mar-2005 03:54
This is a simple function to merge an array multidimensional:
<?php
function multimerge ($array1, $array2) {
if (is_array($array2) && count($array2)) {
foreach ($array2 as $k => $v) {
if (is_array($v) && count($v)) {
$array1[$k] = multimerge($array1[$k], $v);
} else {
$array1[$k] = $v;
}
}
} else {
$array1 = $array2;
}
return $array1;
}
$array1 = array(
1 => "value1",
2 => "value2",
3 => array(
"valor2" => "test3",
),
"more" => array(
"alot" => "A lot of values",
":)" => "Cont"
)
);
$array2 = array(
2 => "other value",
3 => array(
"valor3" => "more values",
),
"more" => array(
"alot" => "Change the value"
),
"final" => "Final Value"
);
print_r(multimerge($array1, $array2));
?>
The output is:
Array
(
[1] => value1
[2] => other value
[3] => Array
(
[valor2] => test3
[valor3] => more values
)
[more] => Array
(
[alot] => Change the value
[:)] => Cont
)
[final] => Final Value
)
19-Mar-2005 10:48
...
function preserved_merge_array( $newArray, $otherArray ) {
foreach( $otherArray as $key => $value)
{
if ( !is_array($newArray[$key]) ) $newArray[$key] = array();
if ( is_array($value) ) $newArray[$key] = preserved_merge_array( $newArray[$key], $value );
else $newArray[$key] = $value;
}
return $newArray;
}
...
20-Jan-2005 10:05
Note that if you put a number as a key in an array, it is eventually converted to an int even if you cast it to a string or put it in quotes.
That is:
$arr["0"] = "Test";
var_dump( key($arr) );
will output int(0).
This is important to note when merging because array_merge will append values with a clashing int-based index instead of replacing them. This kept me tied up for hours.
11-Jan-2005 06:38
Someone posted a function with the note:
"if u need to overlay a array that holds defaultvalues with another that keeps the relevant data"
<?
//about twice as fast but the result is the same.
//note: the sorting will be messed up!
function array_overlay($skel, $arr) {
return $arr+$skel;
}
//example:
$a = array("zero","one","two");
$a = array_overlay($a,array(1=>"alpha",2=>NULL));
var_dump($a);
/* NULL is ignored so the output is:
array(3) {
[1]=>
string(5) "alpha"
[0]=>
string(4) "zero"
[2]=>
string(3) "two"
}
*/
?>
23-Dec-2004 02:57
if you generate form select from an array, you probably want to keep your array keys and order intact,
if so you can use ArrayMergeKeepKeys(), works just like array_merge :
array ArrayMergeKeepKeys ( array array1 [, array array2 [, array ...]])
but keeps the keys even if of numeric kind.
enjoy
<?
$Default[0]='Select Something please';
$Data[147]='potato';
$Data[258]='banana';
$Data[54]='tomato';
$A=array_merge($Default,$Data);
$B=ArrayMergeKeepKeys($Default,$Data);
echo '<pre>';
print_r($A);
print_r($B);
echo '</pre>';
Function ArrayMergeKeepKeys() {
$arg_list = func_get_args();
foreach((array)$arg_list as $arg){
foreach((array)$arg as $K => $V){
$Zoo[$K]=$V;
}
}
return $Zoo;
}
//will output :
Array
(
[0] => Select Something please
[1] => potato
[2] => banana
[3] => tomato
)
Array
(
[0] => Select Something please
[147] => potato
[258] => banana
[54] => tomato
)
?>
24-Nov-2004 10:40
If you have a two dimensional array, or otherwise an array of arrays, the following may be handy: <?call_user_func_array('array_merge', $arr);?>
For instance:
<?php
list($GIF, $JPG, $PNG, $WBMP) = array(1,2,3,15);
$ext_map = array(
$GIF => array('gif'),
$JPG => array('jpg', 'jpeg'),
$PNG => array('png'),
$WBMP => array('wbmp'),
);
$ext_list = call_user_func_array('array_merge', $ext_map);
print_r($ext_list);
?>
Output:
Array
(
[0] => gif
[1] => jpg
[2] => jpeg
[3] => png
[4] => wbmp
)
22-Nov-2004 07:17
This is explained above but may not be exactly clear. If you have two arrays such as:
$Array1 {
[0] => "dog"
}
$Array2 {
[0] => "cat",
[1] => "bird",
[2] => null,
...
[n-1] => null,
[n] => "gator"
}
and you don't want to lose the null values in the final array then do NOT use array_merge. Instead simply use the + operator.
array_merge($Array1,$Array2) gives:
[0] => "dog",
[1] => "cat",
[2] => "bird",
[3] => "gator"
$Array1 + $Array2 gives:
[0] => "dog",
[1] => "cat",
[2] => "bird",
[3] => null,
...
[n-1] => null,
[3] => "gator"
function array_overlay($skel, $arr)
{
foreach ($skel as $key => $val) {
if (!isset($arr[$key])) {
$arr[$key] = $val;
} else {
if (is_array($val)) {
$arr[$key] = array_overlay($val, $arr[$key]);
}
}
}
return $arr;
}
// if u need to overlay a array that holds defaultvalues with another that keeps the relevant data
25-Sep-2004 08:48
I needed to add some values (array) to an array on each loop.
I used merge because it seemed to be the right way. But array_splice() ist much faster:
<?
$merge = array();
$splice = array();
function makearray() { //to do on each loop
//return two values:
return array('foo','bar');
}
for($i=0;$i<1000;$i++) $merge = array_merge($merge,makearray());
echo count($merge); //returns 2000 after about 2 sec (PHP5)
for($i=0;$i<1000;$i++) array_splice($splice, 0,0,makearray());
echo count($splice); //returns 2000 after about 0.8 sec (PHP5)
?>
Note: The sorting will be diffrent but you can use
array_splice($splice, count($splice),0,makearray());
which is still faster (1.4 sec)
24-Aug-2004 12:37
It would seem that array_merge doesn't do anything when one array is empty (unset):
<?php //$a is unset
$b = array("1" => "x");
$a = array_merge($a, $b});
//$a is still unset.
