Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_merge

array_merge

Merge one or more arrays (PHP 4, PHP 5)
array array_merge ( array array1 [, array array2 [, array ...]] )

array_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.

Example 261. array_merge() example

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

The above example will output:

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


Example 262. Simple array_merge() example

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

Don't forget that numeric keys will be renumbered!

Array
(
   [
0] => data
) ?>

If you want to completely preserve the arrays and just want to append them to each other (not overwriting the previous keys), use the + operator:

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

The numeric key will be preserved and thus the association remains.

Array
(
   [
1] => data
) ?>


Warning:

The behavior of array_merge() was modified in PHP 5. Unlike PHP 4, array_merge() now only accepts parameters of type array. However, you can use typecasting to merge other types. See the example below for details.

Example 263. array_merge() PHP 5 example

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

The above example will output:

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


See also array_merge_recursive(), array_combine() and array operators.

Related Examples ( Source code ) » array_merge




Code Examples / Notes » array_merge

niv

[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.


poison

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);
?>


20-jul-2006 04: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...


rcarvalhoremovecaps

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 :-)


barpfotenbaer

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"]);
}
?>


m dot kaczanowski

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;
}
?>


frankb

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.


alberto dot pacheco

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);
}
?>


jae

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"


lito

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
)


tobias_mik

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;
}
?>


hs

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.


kevin campbell

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.


vinicius cubas brand

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
       )
)


asteddy

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;
}
?>


nospam

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"
}
*/
?>


seva-php

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);
}
?>


clancyhood

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


sam_hunting2004

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...


ntpt

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


alec solway

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.


jeff_1089

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 "
";
$array1 = array_merge((array)$itema, $items);
$array2 = array_merge(array($itema), $items);
print "
";
print "
";
print_r($array1);
print "
";
print "
";
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 ) )


biguenique

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;
}
?>


bcraigie

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.


jyee

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.


01-nov-2003 06: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.


kaigillmann

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));
}
?>


snookiex_at_gmail_dot_com

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;
}


jnothman

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
)


frederick.lemasson{at}kik-it.com

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
)
?>


ice

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. :)


ttsgosadow

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 '_'.


tbs2tbs

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 )


lcvalentine

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


zspencer

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)
/*
Array {
cats => Murder the beasties!,
ninjas => Use ninjas to murder cats!,
?>
cats_0 => Cats are fluffy! Hooray for Cats!,
ninjas_0 => Ninjas are mean cat brutalizers!!!
}
function safe_array_merge ()
{
$args = func_get_args();
$result=array();
foreach($args as &$array)
{
foreach($array as $key=>&$value)
{
if(isset($result[$key]))
{
$continue=TRUE;
$fake_key=0;
while($continue==TRUE)
{
if(!isset($result[$key.'_'.$fake_key]))
{
$result[$key.'_'.$fake_key]=$value;
$continue=FALSE;
}
$fake_key++;
}
}
else
{
$result[$key]=$value;
}
}
}
return $result;
}
?>


nospam

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)


freed489

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
?>


marce!

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;
}


loner

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.


joe

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.


sfletcher

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...


j_oaquimsilva

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);
}
?>


anonyme

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 )
?>


mail

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;
       }
?>


komashooter

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("
");
}
?>


rafmavchezlibre_in_france

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!!


17-nov-2004 06: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


03-sep-2003 11: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.


rquadling

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',)


chris

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.


hayley watson

As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.

arduenn

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 ;-)


dercsar

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)


ahigerd

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


herve dot pages

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).


01-nov-2006 02: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;
}
?>


asteddy

/*
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;
}


jimomighty

...
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;
}
...


php

<?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>";
?>


topera

<?
/*
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


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker