PHP 7.0.6 Released

array_merge

(PHP 4, PHP 5, PHP 7)

array_mergeMerge one or more arrays

Description

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

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.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Parameters

array1

Initial array to merge.

...

Variable list of arrays to merge.

Return Values

Returns the resulting array.

Examples

Example #1 array_merge() example

<?php
$array1 
= array("color" => "red"24);
$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 #2 Simple array_merge() example

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

Don't forget that numeric keys will be renumbered!

Array
(
    [0] => data
)

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

<?php
$array1 
= array(=> 'zero_a'=> 'two_a'=> 'three_a');
$array2 = array(=> 'one_b'=> 'three_b'=> 'four_b');
$result $array1 $array2;
var_dump($result);
?>

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Example #3 array_merge() with non-array types

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

The above example will output:

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

See Also

User Contributed Notes

Julian Egelstaff
6 years ago
In some situations, the union operator ( + ) might be more useful to you than array_merge.  The array_merge function does not preserve numeric key values.  If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1
[0] = "zero";
$array1[1] = "one";

$array2[1] = "one";
$array2[2] = "two";
$array2[3] = "three";

$array3 = $array1 + $array2;

//This will result in::

$array3 = array(0=>"zero", 1=>"one", 2=>"two", 3=>"three");

?>

Note the implicit "array_unique" that gets applied as well.  In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian
rajaimranqamer at gmail dot com
1 year ago
to get unique value from multi dimensional array use this instead of array_unique(), because array_unique() does not work on multidimensional:
array_map("unserialize", array_unique(array_map("serialize", $array)));
Hope this will help someone;
Example
$a=array(array('1'),array('2'),array('3'),array('4));
$b=array(array('2'),array('4'),array('6'),array('8));
$c=array_merge($a,$b);
then write this line to get unique values
$c=array_map("unserialize", array_unique(array_map("serialize", $c)));
print_r($c);
Frederick.Lemasson{AT}kik-it.com
11 years ago
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
)

?>
craig ala craigatx.com
5 years ago
Reiterating the notes about casting to arrays, be sure to cast if one of the arrays might be null:

<?php
header
("Content-type:text/plain");
$a = array('zzzz', 'xxxx');
$b = array('mmmm','nnnn');

echo
"1 ==============\r\n";
print_r(array_merge($a, $b));

echo
"2 ==============\r\n";
$b = array();
print_r(array_merge($a, $b));

echo
"3 ==============\r\n";
$b = null;
print_r(array_merge($a, $b));

echo
"4 ==============\r\n";
$b = null;
print_r(array_merge($a, (array)$b));

echo
"5 ==============\r\n";
echo
is_null(array_merge($a, $b)) ? 'Result is null' : 'Result is not null';
?>

Produces:

1 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
    [2] => mmmm
    [3] => nnnn
)
2 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
)
3 ==============
4 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
)
5 ==============
Result is null
anonyme
9 years ago
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 )

?>
ron at ronfolio dot com
7 years ago
I needed a function similar to ian at fuzzygroove's array_interlace, but I need to pass more than two arrays.

Here's my version, You can pass any number of arrays and it will interlace and key them properly.

<?php
function array_interlace() {
   
$args = func_get_args();
   
$total = count($args);

    if(
$total < 2) {
        return
FALSE;
    }
   
   
$i = 0;
   
$j = 0;
   
$arr = array();
   
    foreach(
$args as $arg) {
        foreach(
$arg as $v) {
           
$arr[$j] = $v;
           
$j += $total;
        }
       
       
$i++;
       
$j = $i;
    }
   
   
ksort($arr);
    return
array_values($arr);
}
?>

Example usage:
<?php
$a
= array('a', 'b', 'c', 'd');
$b = array('e', 'f', 'g');
$c = array('h', 'i', 'j');
$d = array('k', 'l', 'm', 'n', 'o');

print_r(array_interlace($a, $b, $c, $d));
?>

result:

Array
(
    [0] => a
    [1] => e
    [2] => h
    [3] => k
    [4] => b
    [5] => f
    [6] => i
    [7] => l
    [8] => c
    [9] => g
    [10] => j
    [11] => m
    [12] => d
    [13] => n
    [14] => o
)

Let me know if you improve on it.
frankb at fbis dot net
12 years ago
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.
w_barath at hotmail dot com
4 years ago
I keep seeing posts for people looking for a function to replace numeric keys.

No function is required for this, it is default behavior if the + operator:

<?php
$a
=array(1=>"one", "two"=>2);
$b=array(1=>"two", "two"=>1, 3=>"three", "four"=>4);

print_r($a+$b);
?>

Array
(
    [1] => one
    [two] => 2
    [3] => three
    [four] => 4
)

How this works:

The + operator only adds unique keys to the resulting array.  By making the replacements the first argument, they naturally always replace the keys from the second argument, numeric or not! =)
clancyhood at gmail dot com
8 years ago
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
gj@php
1 year ago
i did a small benchmark (on  PHP 5.3.3) comparing:
* using array_merge on numerically indexed arrays
* using a basic double loop to merge multiple arrays

the performance difference is huge:

<?php

require_once("./lib/Timer.php");

function
method1($mat){
   
$all=array();
    foreach(
$mat as $arr){
       
$all=array_merge($all,$arr);
    }
    return
$all;
}

function
method2($mat){
   
$all=array();
    foreach(
$mat as $arr){
        foreach(
$arr as $el){
           
$all[]=$el;
        }
    }
    return
$all;
}

function
tryme(){
   
$y=250; //#arrays
   
$x=200; //size per array
   
$mat=array();
   
//build big matrix
   
for($i=0;$i<$y;$i++){
        for(
$j=0;$j<$x;$j++){
           
$mat[$i][$j]=rand(0,1000);
        }   
    }

   
$t=new Timer();
   
method1($mat);
   
$t->displayTimer();
   
   
$t=new Timer();
   
method2($mat);
   
$t->displayTimer();
   
/*
output:
Script runtime: 2.36782 secs. Script runtime: 0.02137 sec.
*/
   
}

tryme();

?>

So that's more than a factor 100!!!!!
Angel I
1 year ago
An addition to what Julian Egelstaff above wrote - the array union operation (+) is not doing an array_unique - it will just not use the keys that are already defined in the left array.  The difference between union and merge can be seen in an example like this:

<?php
$arr1
['one'] = 'one';
$arr1['two'] = 'two';

$arr2['zero'] = 'zero';
$arr2['one'] = 'three';
$arr2['two'] = 'four';

$arr3 = $arr1 + $arr2;
var_export( $arr3 );
# array ( 'one' => 'one', 'two' => 'two', 'zero' => 'zero', )

$arr4 = array_merge( $arr1, $arr2 );
var_export( $arr4 );
# array ( 'one' => 'three', 'two' => 'four', 'zero' => 'zero', )
?>
info at eastghost dot com
7 months ago
We noticed array_merge is relatively slower than manually extending an array:

given:
$arr_one[ 'x' => 1, 'y' => 2 ];
$arr_two[ 'a' => 10, 'b' => 20 ];

the statement:
$arr_three = array_merge( $arr_one, $arr_two );
is routinely 200usec slower than:

$arr_three = $arr_one;
foreach( $arr_two as $k => $v ) { $arr_three[ $k ] = $v; }

200usec didn't matter...until we started combining huge arrays.

PHP 5.6.x
Anonymous
12 years ago
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.
bcraigie at bigfoot dot com
11 years ago
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.
Gemorroj
3 years ago
The function behaves differently with numbers more than PHP_INT_MAX
<?php
$arr1
= array('1234567898765432123456789' => 'dd');
$arr2 = array('123456789876543212345678' => 'ddd', '35' => 'xxx');
var_dump(array_merge($arr1, $arr2));
//
$arr1 = array('1234' => 'dd');
$arr2 = array('12345' => 'ddd', '35' => 'xxx');
var_dump(array_merge($arr1, $arr2));
?>
result:
array(3) {
  ["1234567898765432123456789"]=>
  string(2) "dd"
  ["123456789876543212345678"]=>
  string(3) "ddd"
  [0]=>
  string(3) "xxx"
}
array(3) {
  [0]=>
  string(2) "dd"
  [1]=>
  string(3) "ddd"
  [2]=>
  string(3) "xxx"
}
alejandro dot anv at gmail dot com
4 years ago
WARNING: numeric subindexes are lost when merging arrays.

Check this example:

$a=array('abc'=>'abc','def'=>'def','123'=>'123','xyz'=>'xyz');
echo "a=";print_r($a);
$b=array('xxx'=>'xxx');
echo "b=";print_r($b);
$c=array_merge($a,$b);
echo "c=";print_r($c);

The result is this:

c=Array
(
    [abc] => abc
    [def] => def
    [0] => 123
    [xyz] => xyz
    [xxx] => xxx
)
vladas dot dirzys at gmail dot com
2 years ago
To combine several results (arrays):

<?php
$results
= array(
    array(
        array(
'foo1'),
        array(
'foo2'),
    ),
    array(
        array(
'bar1'),
        array(
'bar2'),
    ),
);

$rows = call_user_func_array('array_merge', $results);
print_r($rows);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => foo1
        )

    [1] => Array
        (
            [0] => foo2
        )

    [2] => Array
        (
            [0] => bar1
        )

    [3] => Array
        (
            [0] => bar2
        )

)

However, example below helps to preserve numeric keys:

<?php
$results
= array(
    array(
       
123 => array('foo1'),
       
456 => array('foo2'),
    ),
    array(
       
321 => array('bar1'),
       
654 => array('bar2'),
    ),
);

$rows = array();
foreach (
$results as &$result) {
   
$rows = $rows + $result; // preserves keys
}
print_r($rows);
?>

The above example will output:
Array
(
    [123] => Array
        (
            [0] => foo1
        )

    [456] => Array
        (
            [0] => foo2
        )

    [321] => Array
        (
            [0] => bar1
        )

    [654] => Array
        (
            [0] => bar2
        )
)
enaeseth at gmail dot com
6 years ago
In both PHP 4 and 5, array_merge preserves references in array values. For example:

<?php
$foo
= 12;
$array = array("foo" => &$foo);
$merged_array = array_merge($array, array("bar" => "baz"));
$merged_array["foo"] = 24;
assert($foo === 24); // works just fine
?>
no_one at nobody dot com
8 years ago
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"
}
Tudor
6 years ago
array_merge will merge numeric keys in array iteration order, not in increasing numeric order. For example:

<?php
$a
= array(0=>10, 1=>20);  // same as array(10, 20);
$b = array(0=>30, 2=>50, 1=>40);
?>

array_merge($a, $b) will be array(10, 20, 30, 50, 40) and not array(10, 20, 30, 40, 50).
Joe at neosource dot com dot au
8 years ago
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.
zagadka at evorg dot dk
5 years ago
Note that if you use + to merge array in order to preserve keys, that in case of duplicates the values from the left array in the addition is used.
allankelly
6 years ago
More on the union (+) operator:
the order of arrays is important and does not agree in my test below
with the other posts. The 'unique' operation preserves the initial key-value and discards later duplicates.

PHP 5.2.6-2ubuntu4.2

<?php
$a1
=array('12345'=>'a', '23456'=>'b', '34567'=>'c', '45678'=>'d');
$a2=array('34567'=>'X');
$a3=$a1 + $a2;
$a4=$a2 + $a1;
print(
'a1:'); print_r($a1);
print(
'a2:'); print_r($a2);
print(
'a3:'); print_r($a3);
print(
'a4:'); print_r($a4);
?>

a1:Array
(
    [12345] => a
    [23456] => b
    [34567] => c
    [45678] => d
)
a2:Array
(
    [34567] => X
)
a3:Array
(
    [12345] => a
    [23456] => b
    [34567] => c
    [45678] => d
)
a4:Array
(
    [34567] => X
    [12345] => a
    [23456] => b
    [45678] => d
)
php at moechofe dot com
10 years ago
<?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>";

?>
carrox at inbox dot lv
7 years ago
Usage of operand '+' for merging arrays:

<?php

$a
=array(
'a'=>'a1',
'b'=>'a2',
'a3',
'a4',
'a5');

$b=array('b1',
'b2',
'a'=>'b3',
'b4');

$a+=$b;

print_r($a);

?>

output:
Array
(
    [a] => a1
    [b] => a2
    [0] => a3
    [1] => a4
    [2] => a5
    [3] => b5
)

numeric keys of elements of array B what not presented in array A was added.

<?php

$a
=array('a'=>'a1','b'=>'a2','a3','a4','a5');
$b=array(100=>'b1','b2','a'=>'b3','b4');

$a+=$b;

print_r($a);

?>

output:

   [a] => a1
    [b] => a2
    [0] => a3
    [1] => a4
    [2] => a5
    [100] => b1
    [101] => b2
    [102] => b4

autoindex for array B started from 100, these keys not present in array A, so this elements was added to array A
ntpt at centrum dot cz
10 years ago
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
Marce!
9 years ago
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;
}
kaigillmann at gmxpro dot net
10 years ago
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));
}
?>
kristopolous at yahoo dot com
2 months ago
I constantly forget the direction of array_merge so this is partially for me and partially for people like me.

array_merge is a non-referential non-inplace right-reduction. For different ctrl-f typers, it's reduce-right, side-effect free, idempotent, and non in-place.

ex:

$a = array_merge(['k' => 'a'], ['k' => 'b']) => ['k' => 'b']
array_merge(['z' => 1], $a) => does not modify $a but returns ['k' => 'b', 'z' => 1];

Hopefully this helps people that constant look this up such as myself.
php at metehanarslan dot com
1 year ago
Sometimes you need to modify an array with another one here is my approach to replace an array's content recursively with delete opiton. Here i used "::delete::" as reserved word to delete items.

<?php
$person
= array(
   
"name" => "Metehan",
   
"surname"=>"Arslan",
   
"age"=>27,
   
"mail"=>"hidden",
   
"favs" => array(
       
"language"=>"php",
       
"planet"=>"mercury",
       
"city"=>"istanbul")
);

$newdata = array(
   
"age"=>28,
   
"mail"=>"::delete::",
   
"favs" => array(
       
"language"=>"js",
       
"planet"=>"mercury",
       
"city"=>"shanghai")
);

print_r(array_overlay($person,$newdata));
// result: Array ( [name] => Metehan [surname] => Arslan [age] => 28 [favs] => Array ( [language] => js [planet] => mercury [city] => shanghai ) )

function array_overlay($a1,$a2)
{
    foreach(
$a1 as $k => $v) {
        if (
$a2[$k]=="::delete::"){
            unset(
$a1[$k]);
            continue;
        };
        if(!
array_key_exists($k,$a2)) continue;
        if(
is_array($v) && is_array($a2[$k])){
           
$a1[$k] = array_overlay($v,$a2[$k]);
        }else{
           
$a1[$k] = $a2[$k];
        }
       
    }
    return
$a1;
}
?>
arifulin at gmail dot com
1 month ago
public function mergeArrays($arrays, $field)
    {
        //take array in arrays for retrive structure after merging
        $clean_array = current($arrays);
        foreach ($clean_array as $i => $value) {
            $clean_array[$i]='';
        }

        $merged_array = [];
        $name = '';
        foreach ($arrays as $array){
            $array = array_filter($array); //clean array from empty values
            if ($name == $array[$field]) {
                $merged_array[$name] = array_merge($merged_array[$name], $array);
                $name = $array[$field];
            } else {
                $name = $array[$field];
                $merged_array[$name] = $array;
            }
        }
        //have to be cleaned from array 'field' signs to return original structure of arrays
        foreach ($merged_array as $array){
            $ready_array[] = array_merge($clean_array, $array);
        }

        return $ready_array;
    }
Anonymous
10 months ago
As PHP 5.6 you can use array_merge + "splat" operator to reduce a bidimensonal array to a simple array:

<?php
$data
= [[1, 2], [3], [4, 5]];
print_r(array_merge(... $data)); // [1, 2, 3, 4, 5];
?>
nekroshorume at gmail dot com
6 years ago
be aware there is a slight difference:

<?php
$array1
= array('lang'=>'js','method'=>'GET');
$array2 = array('lang'=>'php','browser'=>'opera','method'=>'POST');
?>

BETWEEN:

<?php array_merge($array2,$array1); ?>
outputs: Array ( [lang] => js [browser] => opera [method] => GET )

notice that the repeated keys will be overwritten by the ones of $array1, maintaining those, because it is the array that is being merged

AND

<?php array_merge($array1,$array2); ?>
outputs: Array ( [lang] => php [method] => POST [browser] => opera )

here the oposite takes place: array1 will have its elements replaced by those of array2.
njp AT o2 DOT pl
4 years ago
Uniques values merge for array_merge function:

<?php
function array_unique_merge() {
       
       
$variables = '$_'.implode(',$_',array_keys(func_get_args()));

       
$func = create_function('$tab', ' list('.$variables.') = $tab; return array_unique(array_merge('.$variables.'));');
       
        return
$func(func_get_args());
    }
?>

Doesn't work on objects.

Smarter way for uniques values merge array:

<?php
function array_unique_merge() {
      
       return
array_unique(call_user_func_array('array_merge', func_get_args()));
   }
?>

Example 1:

$a = array(1,2);
$b = array(2,3,4);

array_unique_merge($a,$b);

Return:
array(1,2,3,4);

Example 2:

$a = array(1,2);
$b = array(2,3,4);
$c = array(2,3,4,5);

array_unique_merge($a,$b);

Return:
array(1,2,3,4,5);

Doesn't work on objects.
jpakin at gmail dot com
5 years ago
I had a hard time using array_merge with large datasets. By the time my web framework was in memory there wasn't enough space to have multiple copies of my dataset. To fix this I had to remove any functions which operated on the data set and made a copy in memory (pass by value).

I realize the available memory to an application instance is modifiable, but I didn't think I should have to set it below the default 16mb for a web app!

Unfortunately, a number of php functions pass by value internally, so I had to write my own merge function. This passes by reference, utilizes a fast while loop (thus doesn't need to call count() to get an upper boundary, also a php pass by value culprit), and unsets the copy array (freeing memory as it goes).

<?php

function mergeArrays(&$sourceArray, &$copyArray){
       
//merge copy array into source array
               
$i = 0;
        while (isset(
$copyArray[$i])){
           
$sourceArray[] = $copyArray[$i];
            unset(
$copyArray[$i]);
           
$i++;
        }
    }
?>

This fixed the problem. I would love to know if there is an even faster, more efficient way. Simply adding the two arrays won't work since there is an overlap of index.
nzujev [AT] gmail [DOT] com
5 years ago
Be ready to surprise like this one.
array_merge renumbers numeric keys even if key is as string.
keys '1' & '2' will be updated to 0 & 1, but '1.1' & '1.2' remain the same, but they are numeric too (is_numeric('1.1') -> true)

It's better to use '+' operator or to have your own implementation for array_merge.

<?php

$x1
= array (
   
'1'     => 'Value 1',
   
'1.1'   => 'Value 1.1',
);

$x2 = array (
   
'2'     => 'Value 2',
   
'2.1'   => 'Value 2.1',
);

$x3 = array_merge( $x1, $x2 );

echo
'<pre>NOT as expected: '. print_r( $x3, true ) .'</pre>';

$x3 = $x1 + $x2;

echo
'<pre>As expected: '. print_r( $x3, true ) .'</pre>';

?>

NOT as expected: Array
(
    [0] => Value 1
    [1.1] => Value 1.1
    [1] => Value 2
    [2.1] => Value 2.1
)
As expected: Array
(
    [1] => Value 1
    [1.1] => Value 1.1
    [2] => Value 2
    [2.1] => Value 2.1
)
Hayley Watson
8 years ago
As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.
david_douard at hotmail dot com
7 years ago
To avoid REINDEXING issues,

use + operator :

array_merge(
          array("truc" => "salut"),
          array("machin" => "coucou")
        )

returns

array(2)
{
[0] => string() "salut"
[1] => string() "coucou"
}

whereas

array("truc" => "salut") + array("machin" => "coucou")

returns

array(2)
{
["truc"] => string() "salut"
["machin"] => string() "coucou"
}
bishop
8 years ago
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"
}
Julian Egelstaff
6 years ago
More about the union operator (+)...

The "array_unique" that gets applied, is actually based on the keys, not the values.  So if you have multiple values with the same key, only the last one will be preserved.

<?php

$array1
[0] = "zero";
$array1[1] = "one";

$array2[0] = 0;
$array1[1] = 1;

$array3 = $array1 + $array2;

// array3 will look like:
// array(0=>0, 1=>1)
// ie: beware of the latter keys overwriting the former keys

?>
BigueNique at yahoo dot ca
9 years ago
Needed an quick array_merge clone that preserves the keys:

<?php
// 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;
}
?>
dercsar at gmail dot com
9 years ago
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)
hs at nospam dot magnum-plus dot com
10 years ago
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.
RQuadling at GMail dot com
8 years ago
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',)
ahigerd at stratitec dot com
9 years ago
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
Anonymous
9 years ago
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;
}
?>
poison
9 years ago
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);
?>
Alec Solway
11 years ago
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 years ago
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"
}
*/
?>
tobias_mik at hotmail dot com
12 years ago
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;
}
?>
rcarvalhoREMOVECAPS at clix dot pt
12 years ago
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 :-)
loner at psknet dot !NOSPAM!com
12 years ago
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.
izhar_aazmi at gmail dot com
4 years ago
The problem that the array keys are reindexed, and further not working on array values of type object or other mixed types.

Simply, I did this:

<?php
foreach($new as $k => $v)
{
   
$old[$k] = $v;
}
// This will overwrite all values in OLD with any existing
// matching value in NEW
// And keep all non matching values from OLD intact.
// No reindexing, and complete overwrite
/// Working with all kind of data
?>
zspencer at zacharyspencer dot com
9 years ago
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;
}
?>
chris at luethy dot net
9 years ago
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.
riddlemd at gmail dot com
6 years ago
Apparently there is a shorthand that works very much like array_merge. I figured I would leave a comment here, sense I saw it used in code but found nothing about it from google searches.

<?php
$array
= array(
'name' => 'John Doe'
);
$array += array(
'address' => 'someplace somestreet'
);

echo
$array['address']; // Outputs 'someplace somestreet'
?>

A difference from merge_array, it does NOT overwrite existing keys, regardless of key type.
jerry at gii dot co dot jp
7 years ago
There was a previous note that alluded to this, but at least in version 5.2.4 array_merge will return NULL if any of the arguments are NULL. This bit me with $_POST when none of the controls were successful.
Janez R.
2 years ago
Please note that -1 is a numeric key and will be reindexed.
Less obvious numeric keys are also '-1' (becomes -1) and -1.5 (becomes -1).

'-1a', however, is not a numeric key and you could exploit the fact that '-1a' == -1 evaluates to true in php (just a hint). But as this is not very efficient, operator + may be a better option.

<?php
$arr
= array(-1=> "-1", '-2'=> "'-2'", -3.5=> "-3.5", '-4a'=> "'-4a'");
print_r(array(
   
$arr,
   
array_merge($arr,array()),
   
'-1a' == -1,
));
?>

Result:

Array
(
    [0] => Array
        (
            [-1] => -1
            [-2] => '-2'
            [-3] => -3.5
            [-4a] => '-4a'
        )

    [1] => Array
        (
            [0] => -1
            [1] => '-2'
            [2] => -3.5
            [-4a] => '-4a'
        )

    [2] => 1
)
To Top