array_merge

(PHP 4, PHP 5, PHP 7, PHP 8)

array_mergeFonde uno o più array

Descrizione

array_merge(array $array1, array $array2 = ?, array $... = ?): array

array_merge() fonde gli elementi di uno o più array in modo che i valori di un array siano accodati a quelli dell'array precedente. Restituisce l'array risultante.

Se gli array in input hanno le stesse chiavi stringa, l'ultimo valore di quella chiave sovrascriverà i precedenti. Comunque, se gli array hanno le stesse chiavi numeriche, l'ultimo valore non sovrascriverà quello originale, bensì sarà accodato.

Se viene fornito un solo array, e questo è indicizzato numericamente, le chiavi vengono reindicizzate in una sequenza continua. Nel caso di array associativi, delle chiavi duplicate rimane solo l'ultima. Vedere l'esempio tre per ulteriori dettagli.

Example #1 Esempio di array_merge()

<?php
$array1
= array("colore" => "rosso", 2, 4);
$array2 = array("a", "b", "colore" => "verde", "forma" => "trapezio", 4);
$risultato = array_merge($array1, $array2);
print_r($risultato);
?>

La variabile $risultato sarà:

Array
(
    [colore] => verde
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [forma] => trapezio
    [4] => 4
)

Example #2 Esempio di array_merge()

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

Non dimenticarsi che le chiavi numeriche saranno rinumerate!

Array
(
    [0] => data
)

Se si vogliono preservare gli array e li si vuole solo concatenare, usare l'operatore +:

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

La chiave numerica sarà preservata e così pure l'associazione.

Array
(
    [1] => data
)

Example #3 esempio di array_merge()

<?php
$array_uno
= array(0 => "mario", 1 => "roberto", 2 => "andrea", 3 => "dante");
$array_due = array("mario => "roberto", "andrea" => "dante", "mario" => "giacomo");

unset(
$array_uno[2]);

$risultato_uno = array_merge($array_uno);
$risultato_due = array_merge($array_due);

print_r(
$risultato_uno);
print_r(
$risultato_due);
?>

Il risultato sarà:

Array
(
    [0] => mario
    [1] => roberto
    [2] => dante
)
Array
(
    [mario] => giacomo
    [andrea] => dante
)

Nota:

Le chiavi condivise verranno sovrascritte dalla prima chiave processata.

Vedere anche array_merge_recursive() e array_combine() e operatori sugli array.

add a note add a note

User Contributed Notes 48 notes

up
260
Julian Egelstaff
14 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
up
9
titum at lavache dot com
6 years ago
foreach loop is faster than array_merge to append values to an existing array, so choose the loop instead if you want to add an array to the end of another.

<?php
// Create an array of arrays
$chars = [];
for (
$i = 0; $i < 15000; $i++) {
   
$chars[] = array_fill(0, 10, 'a');
}

// test array_merge
$new = [];
$start = microtime(TRUE);
foreach (
$chars as $splitArray) {
   
$new = array_merge($new, $splitArray);
}
echo
microtime(true) - $start; // => 14.61776 sec

// test foreach
$new = [];
$start = microtime(TRUE);
foreach (
$chars as $splitArray) {
    foreach (
$splitArray as $value) {
       
$new[] = $value;
    }
}
echo
microtime(true) - $start; // => 0.00900101 sec
// ==> 1600 times faster
?>
up
53
woodongwong at gmail dot com
6 years 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];
?>

PHP < 5.6:

<?php
$data
= [[1, 2], [3], [4, 5]];
print_r(array_reduce($data, 'array_merge', []));   // [1, 2, 3, 4, 5];

?>
up
44
Angel I
9 years 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', )
?>
up
8
matias dot r dot ventura at gmail dot com
5 years ago
Note that if you want to append one array to another, using a foreach in conjuction with array_push is A LOT faster:

<?php

$array
= array("one", "two", "three", "four");
$test1 = array();
$test2 = array();
$mctime = microtime(true);

for(
$i = 0; $i < 10000; $i++){
   
$test1 = array_merge($test1, $array);
}

echo(
"Test 1: ". (microtime(true) - $mctime) ."s     ");
$mctime = microtime(true);

for(
$i = 0; $i < 10000; $i++){
    foreach(
$array as $value){
       
array_push($test2, $value);
    }
}

echo(
"Test 2: ". (microtime(true) - $mctime) ."s     ");
?>

This in my case resolves to:

Test 1: 2.7962880134583s
Test 2: 0.0039298534393311s
up
10
souzacomprog at gmail dot com
4 years ago
Sometimes we need to traverse an array and group / merge the indexes so that it is easier to extract them so that they are related in the iteration.

<?php

$people
= [
    [
'id' => 1, 'name' => 'Hayley'],
    [
'id' => 2, 'name' => 'Jack', 'dad' => 1],
    [
'id' => 3, 'name' => 'Linus', 'dad' => 4],
    [
'id' => 4, 'name' => 'Peter'],
    [
'id' => 5, 'name' => 'Tom', 'dad' => 4],
];

// We set up an array with just the children
function children($dad, $people)
{
   
$children = [];
    foreach (
$people as $p) {
        if (!empty(
$p["dad"]) && $p["dad"] == $dad["id"]) {
           
$children[] = $p;
        }
    }

    return
$children;
}

$family = [];

// We merge each child with its respective parent
foreach ($people as $p) {
   
$children = children($p, $people);
    if (
$children != []) {
       
$family[] = array_merge($p, ["children" => $children]);
    }
}

print_r($family);

?>

//OUTPUT

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Hayley
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [name] => Jack
                            [dad] => 1
                        )

                )

        )

    [1] => Array
        (
            [id] => 4
            [name] => Peter
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [name] => Linus
                            [dad] => 4
                        )

                    [1] => Array
                        (
                            [id] => 5
                            [name] => Tom
                            [dad] => 4
                        )

                )

        )

)
up
5
makjoybd [at] gmail [dot] com
4 years ago
$a = array(1,2,3);    // an array
$b = 5;  // anything but not an array

$c = array_merge($a, $b); // shows a PHP warning: Argument #2 is not an array

var_dump($c); // output as NULL

// now merge in reverse order
$d = array_merge($b, $a); // shows a PHP warning: Argument #1 is not an array

var_dump($d); // output as NULL

NOTE: For any operation that relies on the previous array merge operation it is highly necessary to check the arguments as well as the result of the merge are arrays before continuing  as the warning would not stop the operation and this might result in data loss and what not... and this should also be stated in the .documentation. Example #3 somewhat started to demonstrate this but used type casting which made this irrelevant to this matter.
up
7
Anonymous
8 years 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];
?>
up
3
BigueNique at yahoo dot ca
17 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;
}
?>
up
11
kristopolous at yahoo dot com
8 years 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.
up
7
Alec Solway
19 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.
up
4
bishop
15 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"
}
up
15
craig ala craigatx.com
13 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
up
14
Frederick.Lemasson{AT}kik-it.com
19 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
)

?>
up
12
rajaimranqamer at gmail dot com
9 years 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);
up
14
w_barath at hotmail dot com
12 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! =)
up
1
padina
6 years ago
Static functions of Classes  with Namespace are callables too.

namespace Vendor\Extension\Service;

class SvgFormationService implements \TYPO3\CMS\Core\SingletonInterface
{

    public static function doubleQuote($value) {
        return '"'.$value.'"';
    }

    public static function otherFunc ($value) {
        $tagAttributes = array_map('\Vendor\Extension\Service\SvgFormationService::doubleQuote',$tagAttributes);
    }
}
up
4
php at metehanarslan dot com
9 years 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;
}
?>
up
7
jcmarchi at gmail dot comfive
7 years ago
It is not officially documented but it is summarily important information for everyone to know: neither array_merge or array_merge_recursive functions will function correctly if non-array objects  are used as parameters.

You would probably expect these functions to ignore non-array elements, right? However, if one parameter is null it PHP will not only return null for the entire function but will also (not always) raise an error, such as :

    [ Warning: array_merge(): Argument #x is not an array... ]

This error message won't appear if the defective variable is an empty array (an empty array is still an array), but it will result in an undesirable incomplete Array.

There are several solutions for this problem by validating the Arrays before use them in these functions, but the most efficient way is to enforce the element as an array directly in the function itself. I.e.:

$merged = array_merge( (array)$first_array, (array)$second_array );
up
9
rameezsoomro dot pk at live dot com
7 years ago
Array merge will return null if any parameter not an array
<?php
$DB_user_result
DB::select()->where()->get(); // return null if not found.
$DB_exists_user_info = ['name'=>'Rameez Soomro','Location'=>'Karachi, Sindh, Pakistan'];
print_r(array_merge($DB_user_result, $DB_exists_user_info));  //NULL
?>
Here is function for solution of array_merge
function copied from  http://sdtuts.com/php-array_merge-function-issue/
<?php
function merge_arrays_obj(){
 
$func_info = debug_backtrace();
 
$func_args = $func_info[0]['args'];
 
$return_array_data = array();
  foreach(
$func_args as $args_index=>$args_data){
    if(
is_array($args_data) || is_object($args_data)){
   
$return_array_data = array_merge($return_array_data,$args_data);
    }
  }
  return
$return_array_data;
}
?>

Code example how to use it
<?php
$array
= array('abc'=>'abcparam');
$null_array = null;
$new_arraydata = array('username'=>'Rameez Soomro','usersite'=>'http://sdtuts.com');
$new_arrayOBJ = array ( (object) array('obj_DATA' => 'ABC_OBJ','obj_next_index '=>'ABC_OBJ_NEXT_INDEX') );
$new_array_data = merge_arrays_obj($array,$null_array,$new_arraydata,$new_arrayOBJ);
print_r($new_array_data);
?>
up
3
fsb at thefsb dot org
4 years ago
We no longer need array_merge() as of PHP 7.4.

    [...$a, ...$b]

does the same as

    array_merge($a, $b)

and can be faster too.

https://wiki.php.net/rfc/spread_operator_for_array#advantages_over_array_merge
up
5
alejandro dot anv at gmail dot com
12 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
)
up
3
tobias_mik at hotmail dot com
20 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;
}
?>
up
1
loner at psknet dot !NOSPAM!com
20 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.
up
5
enaeseth at gmail dot com
14 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
?>
up
3
gj@php
9 years 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!!!!!
up
2
withtvpeter at gmail dot com
5 years ago
Suffice to add, array_merge() creates a new array from the supplied array(s) and does not modify the supplied array(s). Example:

$array1 = ["a" => "one", "b"=>"two"];
$array2 = [ "c" => "three", "d" => "four"];

$mergedArray = array_merge($array1, $array2);

print_r($mergedArray); // => ["a"=> "one", "b"=> "two", "c"=>"three", "d"=>"four"];
print_r($array1);  //=> ["a"=>"one", "b"=>"two"];
up
5
bcraigie at bigfoot dot com
19 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.
up
5
zagadka at evorg dot dk
13 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.
up
8
Gemorroj
11 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"
}
up
8
ron at ronfolio dot com
15 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.
up
3
info at eastghost dot com
8 years 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
up
7
frankb at fbis dot net
20 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.
up
4
carrox at inbox dot lv
15 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
up
5
vladas dot dirzys at gmail dot com
10 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
        )
)
up
4
ntpt at centrum dot cz
18 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
up
6
Anonymous
20 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.
up
5
Tudor
14 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).
up
1
arifulin at gmail dot com
8 years 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;
    }
up
4
clancyhood at gmail dot com
16 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
up
2
Joe at neosource dot com dot au
16 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.
up
2
kaigillmann at gmxpro dot net
18 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));
}
?>
up
1
Hayley Watson
16 years ago
As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.
up
1
Md. Abutaleb
4 years ago
<?php
/* Please note that, the array_merge() function replaces the first key by the second key if both arrays contain the same key. But consider the following code where key '3' is string not integer. In that case ('3') is consider as numeric and generating new numeric key instead of replacing by second one to first one
*/

$array1 = array(0 => 'zero_a', 2 => 'two_a', '3' => 'three_a', 'name' => 'First Name');
$array2 = array(1 => 'one_b', 2 => 'Two b', '3' => 'three_b', 'name' => 'Second Name');

$output = array_merge($array1, $array2);

print_r($output);
Array
(
    [
0] => zero_a
   
[1] => two_a
   
[2] => three_a
   
[name] => Second Name
   
[3] => one_b
   
[4] => Two b
   
[5] => three_b
)

//Hope it will helpful.
?>
up
0
ian_channing at hotmail dot com
6 years ago
array_merge is the equivalent of concat in other languages. I tried to submit a bug that array_concat should be created as an alias to this but it was rejected on the basis they didn't want to polute the namespace and that the documentation should be updated instead. So here's what I put in the bug #73576:

There is no documented array concatenation function. This is a very common function, e.g. Javascript and Ruby have the `concat` function, Python has `+` and Haskell has `++`.

The `array_merge` function is what has be used if you want to concatenate arrays. However it is not mentioned in the documentation (not even in the comments) of that method that that is what should be used.

I propose that `array_concat` be created as an alias of `array_merge`. The concatenation of an associative array is also consistent with trying to merge the hash maps. For example there is a Stack Overflow question on 'concatenating two dictionaries' that is marked as a duplicate of the function 'How to merge two Python dictionaries'. That is, it is consistent that hash map concatenation is the same as hash map merging.

So I believe that `array_concat` is a perfect alias for `array_merge` in terms of numeric arrays and a valid (albeit unnecessary) alias for associative arrays.

This will help almost all developers coming to PHP from other dynamic languages.
up
0
RQuadling at GMail dot com
16 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',)
up
-1
pike-common at kw dot nl
5 years ago
When mixing string keys and numeric keys, numeric keys are still renumbered after merge.

<?php
        $test1
= array("foo"=>"rfoo1",2=>"r21","bar"=>"rbar1");
       
$test2= array("foo"=>"rfoo2",2=>"r22","bar"=>"rbar2");
       
var_dump(array_merge($test1,$test2));
?>
  array(4) {
    ["foo"]=>
    string(5) "rfoo2"
    [0]=>
    string(3) "r21"
    ["bar"]=>
    string(5) "rbar2"
    [1]=>
    string(3) "r22"
}

adding arrays doesn't:

<?php
        var_dump
($test2+$test1);
?>
  array(3) {
    ["foo"]=>
    string(5) "rfoo2"
    [2]=>
    string(3) "r22"
    ["bar"]=>
    string(5) "rbar2"
  }
up
-3
ousseni dot work at gmail dot com
4 years ago
A good function to merge by keys

/**
* @param $array1....$arrayn
*/
public function array_merge_keys(){
     $args = func_get_args();
     $result = array();
     foreach($args as $array)
     {
            foreach($array as $key=>$value)
            {
                $result[$key] = $value;
            }
        }
     return $result;
}
To Top