array_merge

(PHP 4, PHP 5)

array_merge -- 合并一个或多个数组

说明

array array_merge ( array array1 [, array array2 [, array ...]] )

array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。

如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。

例子 1. array_merge() 例子

<?php
$array1
= array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

上例将输出:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

例子 2. 简单的 array_merge() 例子

<?php
$array1
= array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

别忘了数字键名将会被重新编号!

Array
(
    [0] => data
)

如果你想完全保留原有数组并只想新的数组附加到后面,用 + 运算符:

<?php
$array1
= array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
?>

数字键名将被保留从而原来的关联保持不变。

Array
(
    [1] => data
)

警告

array_merge() 的行为在 PHP 5 中被修改了。和 PHP 4 不同,array_merge() 现在只接受 array 类型的参数。不过可以用强制转换来合并其它类型。请看下面的例子。

例子 3. array_merge() PHP 5 例子

<?php
$beginning
= 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

上例将输出:

Array
(
    [0] => foo
    [1] => bar
)

参见 array_merge_recursive()array_combine()数组运算符


add a note add a note User Contributed Notes
01-Nov-2006 10:47
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;
}
?>
BigueNique at yahoo dot ca
29-Sep-2006 10: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;
}
?>
poison
12-Sep-2006 08: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);
?>
dercsar at gmail dot com
05-Sep-2006 04: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)
20-Jul-2006 11:45
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...
anonyme
20-Jul-2006 09: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 )

?>
sfletcher at abcoa dot com
20-Jul-2006 12: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...
chris at luethy dot net
13-Jul-2006 08: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.
freed489 at gmail dot com
18-May-2006 11: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
?>
j_oaquimsilva at yahoo dot com dot br
16-Jan-2006 05: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);

}
?>
seva-php at zend dot com
05-Jan-2006 05: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);
}

?>
hs at nospam dot magnum-plus dot com
30-Dec-2005 06: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.
snookiex_at_gmail_dot_com
10-Dec-2005 10: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;
}
ttsgosadow at gmail dot com
17-Nov-2005 06: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 '_'.
kaigillmann at gmxpro dot net
02-Nov-2005 07: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));
}
?>
topera at gmail dot com
07-Oct-2005 07: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
tbs2tbs at hotmail dot com
01-Sep-2005 02: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 )
php at moechofe dot com
20-Jul-2005 07: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>";

?>
ntpt at centrum dot cz
14-Jul-2005 09: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
Barpfotenbaer
10-Jul-2005 12: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"]);
}
?>
herve dot pages at free dot fr
09-Jul-2005 02: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).
arduenn at gmail dot com
07-Jul-2005 01: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 ;-)
alberto dot pacheco at itesm dot mx
25-May-2005 12: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);
}

?>
rafmavCHEZlibre_in_france
20-Apr-2005 07: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, rsultats:

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 rsultat:
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!!
Vinicius Cubas Brand
15-Apr-2005 12: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
       )
)
jeff_1089 at yahoo dot com
07-Apr-2005 04: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 ) )
lito at eordes dot com
21-Mar-2005 07: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
)
Jimomighty
20-Mar-2005 02: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;
}

...
Alec Solway
21-Jan-2005 02: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.
nospam at veganismus dot ch
11-Jan-2005 10: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"
}
*/
?>
Frederick.Lemasson{AT}kik-it.com
23-Dec-2004 06: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
)

?>
jnothman at student dot usyd dot edu dot au
25-Nov-2004 02: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
)
Jae
22-Nov-2004 11: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"
18-Nov-2004 02:22
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
nospam at veganismus dot ch
25-Sep-2004 11: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)
bcraigie at bigfoot dot com
25-Aug-2004 03: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.
?>

to fix this omit $a if it is unset:-

<?php
if(!IsSet($a)) {
  
$a = array_merge($b);
} else {
 
$a = array_merge($a, $b);
}
?>

I don't know if there's a better way.
niv at NOSPAM iaglans dot DE
13-Jun-2004 01:18
[Editor's Note: If the keys are truly numeric, array_merge will do the trick. But if they are strings, as the example below, you can use array_merge(array_values($array1), array_values($array2)); since it's more beautiful. -- victor@php.net]

i recognized there is no function with that you can add two number-Arrays:

Example:

<?php
// you have two arrays:

array1 = array (['0'] =>"blahblupp",
                       [
'1'] => "bluppblah" );

array2 = array (['0'] =>"tirili",
                       [
'1'] => "tralala" );

// and want following as a result:

result = array (['0'] =>"blahblupp",
                     [
'1'] => "bluppblah",
                     [
'2'] =>"tirili",
                     [
'3'] => "tralala" );

// following function does the addition:

function array_add($array1, $array2)
{
  
$result = $array1;
  
$h = sizeof($array1);
   for (
$i = 0; $i < sizeof($array2); $i++)
   {
      
$result[$h] = $array2[$i];
      
$h++;
   }
  
   return
$result;
}
?>

just added because I didn't find a ready-to-use script here.
mail at nospam dot iaindooley dot com
09-Apr-2004 12:37
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;
       }
?>
frankb at fbis dot net
25-Feb-2004 08:02
to merge arrays and preserve the key i found the following working with php 4.3.1:

<?php
$array1
= array(1 => "Test1", 2 => "Test2");
$array2 = array(3 => "Test3", 4 => "Test4");

$array1 += $array2;
?>

dont know if this is working with other php versions but it is a simple and fast way to solve that problem.
KOmaSHOOTER at gmx dot de
08-Nov-2003 02:03
Here is something for splitting a sorted array into group array  ( sorting the group arrays ) and then merging them together
Note: merge is  like concat in Flash ActionScript :)
In this example i have 3 different  groups in one array

* First the mainArray is sorted for the group entrys
* building from part arrays
* building  copy arrays from  part arrays ( for making the array beginning with  [0] !! )
* merging all part arrays together

0. sorting the main array
1. apportionment from the main array
when the group is changing , a new array is build (part
array ) ! attention at the second  part array !! Array values
are are not beginning with [0]!!
2. making the copy from the part array .
array values are pushed in the new array
3. echo for every array entry
4. overwriting the old array with the new copy
5. part arrays are sorted by function (arrays had been naughted by function array_copy ( Array is beginning with [0] ! )
6. merging the part arrays

Here is the same that i posted before but a bit better solved
array_push (${"activ_array".$j}, $activ_array[$i]); makes the part arrays starting with [0] :)

<?php
$activ_array
=array(
array(
"apfel_01","germany","xx","red"),
array(
"apfel_07","germany","xx","green"),
array(
"apfel_08","germany","xx","green"),
array(
"apfel_02","germany","xx","red"),
array(
"apfel_03","germany","xx","red"),
array(
"apfel_04","germany","xx","red"),
array(
"apfel_09","germany","xx","red_+_green"),
array(
"apfel_10","germany","xx","red_+_green"),
array(
"apfel_05","germany","xx","green"),
array(
"apfel_06","germany","xx","green")
);
function
array_sort($array, $key , $target){
for (
$i = 0; $i < sizeof($array); $i++){
 
$array2 = $array;
 if(
$target == 'name'){
   if(! empty(
$array2[$i]["nameletter"])){
    
//echo $myarray[$i]["nameletter"] ;
    
$array2[$i]["name"] = substr($array2[$i][$key],($array2[$i]["nameletter"]-1));
   }else{
    
$array2[$i]["name"] = substr($array2[$i][$key],0);
   }
  
$sort_values[$i] = $array2[$i]["name"];
   }else{
  
$sort_values[$i] = $array2[$i][$key];
 }
}
 
asort ($sort_values);
 
reset ($sort_values);
  while (list (
$arr_keys, $arr_values) = each ($sort_values)) {
        
$sorted_arr[] = $array[$arr_keys];
  }
  return
$sorted_arr;
}
$activ_array = array_sort($activ_array,3,'imagetype');
$j=0;
// first part array
${"activ_array"."$j"} = array();
for(
$i=0;$i<sizeof($activ_array);$i++){
 if(
$activ_array[$i][3] !=$activ_array[$i-1][3] && $i >1){
  
$j++;
   ${
"activ_array".$j} = array();
 }
array_push (${"activ_array".$j}, $activ_array[$i]);
}
// part array sorting
for($i=0;$i<=$j;$i++){
 ${
"activ_array".$i} = array_sort(${"activ_array".$i},0,'name');
}
$activ_array = array();
for(
$i=0;$i<=$j;$i++){
 
$activ_array = array_merge($activ_array,${"activ_array".$i});
}
for(
$i=0;$i<sizeof($activ_array);$i++){
print_r($activ_array[$i]);
echo(
"<br>");
}

?>
rcarvalhoREMOVECAPS at clix dot pt
04-Nov-2003 04:43
While searching for a function that would renumber the keys in a array, I found out that array_merge() does this if the second parameter is null:

Starting with array $a like:

<?php
Array
(
   [
5] => 5
  
[4] => 4
  
[2] => 2
  
[9] => 9
)
?>

Then use array_merge() like this:

<?php
$a
= array_merge($a, null);
?>

Now the $a array has bee renumbered, but maintaining the order:

<?php
Array
(
   [
0] => 5
  
[1] => 4
  
[2] => 2
  
[3] => 9
)
?>

Hope this helps someone :-)
01-Nov-2003 02:08
In all PHP 4 versions the above function deals gracefully with paramaters which are NOT arrays(). So if you pass a string or number it will be automagically converted to an one-element array as described in the manual section about Types and "implicit typecasting". So if you ever happen to put an empty/unset variable (NULL value) as parameter, array_merge() will still collapse the other arrays as intended.

From PHP5beta2 on this behaviour changed, and PHP will correctly issue a E_WARNING message, whenever one of the paramters isn't an array. So if you ever happen to be uncertain about the contents of a variable passed as parameter to array_merge() you should use explicit typecasting:

<?php
$a
= array(1, 2, 3);
$b = 4;    #-- beware: this is no array!

$result = array_merge(  (array)$a, (array)$b,  ... );
?>

This way $result still would get == array(1, 2, 3, 4); where otherwise the parameters would get rejected with the warning message telling you so.
loner at psknet dot !NOSPAM!com
30-Sep-2003 06:00
I got tripped up for a few days when I tried to merge a (previously serialized) array into a object. If it doesn't make sense, think about it... To someone fairly new, it could... Anyway, here is what I did:
(It's obviously not recursive, but easy to make that way)
<?php
function array_object_merge(&$object, $array) {
   foreach (
$array as $key => $value)
      
$object->{$key} = $value;
}
?>

Simple problem, but concevibly easy to get stuck on.
ice at lazybytes dot net
05-Sep-2003 06:31
I, too have found array_merge_clobber() useful. I use it in a loop to append data to an array. However, when the loop first runs, there will be an error message displayed as array one is empty, so, here is a little fix:

<?php
function array_merge_clobber($arrOne,$arrTwo) {
   if(!
is_array($arrOne) || !is_array($arrTwo)) return false;

  
$arrNewArray = $arrOne;
   forEach (
$arrTwo as $key => $val) {
       if (isSet(
$arrNewArray[$key])) {
           if (
is_array($val) && is_array($arrNewArray[$key])) {
              
$arrNewArray[$key] = array_merge_clobber($arrNewArray[$key], $val);
           }
           else {
              
$arrNewArray[$key] = $val;
           }
       }
       else {
          
$arrNewArray[$key] = $val;
       }
   }
   return
$arrNewArray;
}
?>

Not sure if someone else has already got something similar or better, but this is simple and works for me. :)
04-Sep-2003 06:10
For those who are getting duplicate entries when using this function, there is a very easy solution:

wrap array_unique() around array_merge()

cheers,

k.
tobias_mik at hotmail dot com
25-Jul-2003 08:14
This function merges any number of arrays and maintains the keys:

<?php
function array_kmerge ($array) {
 
reset($array);
 while (
$tmp = each($array))
 {
  if(
count($tmp['value']) > 0)
  {
  
$k[$tmp['key']] = array_keys($tmp['value']);
  
$v[$tmp['key']] = array_values($tmp['value']);
  }
 }
 while(
$tmp = each($k))
 {
  for (
$i = $start; $i < $start+count($tmp['value']); $i ++)$r[$tmp['value'][$i-$start]] = $v[$tmp['key']][$i-$start];
 
$start = count($tmp['value']);
 }
 return
$r;
}
?>