PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_multisort> <array_merge_recursive
Last updated: Fri, 05 Sep 2008

view this page in

array_merge

(PHP 4, PHP 5)

array_mergeMerge one or more arrays

Description

array array_merge ( array $array1 [, array $array2 [, 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.

If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

Parameters

array1

Initial array to merge.

array

Variable list of arrays to recursively 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 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(=> "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 #3 array_merge() PHP 5 example

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



array_multisort> <array_merge_recursive
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
array_merge
carrox at inbox dot lv
01-Sep-2008 02:41
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
ron at ronfolio dot com
12-Aug-2008 04:44
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.
david_douard at hotmail dot com
02-Jul-2008 12:41
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"
}
monkey dot 05 dot 06 at NO SPAM gmail dot com
17-Jun-2008 07:25
I wrote this function to strip one or more arrays to a single one-dimensional array. Keys assigned to individual values are preserved; keys assigned to arrays are not.

<?php
 
function array_merge_deep($arr) { // an array-merging function to strip one or more arrays down to a single one dimension array
   
$arr = (array)$arr;
   
$argc = func_num_args();
    if (
$argc != 1) {
     
$argv = func_get_args();
      for (
$i = 1; $i < $argc; $i++) $arr = array_merge($arr, (array)$argv[$i]);
    }
   
$temparr = array();
    foreach(
$arr as $key => $value) {
      if (
is_array($value)) $temparr = array_merge($temparr, array_merge_deep($value));
      else
$temparr = array_merge($temparr, array($key => $value));
    }
    return
$temparr;
  }
?>

Example:

<?php
  $groceries
= array("fruits" => array("apples", "bananas", "cherries", "grapes"), "dry goods" => array("bread", "flour", "yeast"), "dairy" => "milk");
 
$groceries = array_merge_deep($groceries);
  echo
"<pre>"; print_r($groceries); echo "</pre>";
?>

Yields the following:

Array
(
    [0] => apples
    [1] => bananas
    [2] => cherries
    [3] => grapes
    [4] => bread
    [5] => flour
    [6] => yeast
    [dairy] => milk
)
david dot lay at axlr8 dot com
08-May-2008 04:19
probably simpler versions of this (below) but thought i'd post my solution up as it might be helpful :)

<?php
function array_merge_php4_comp() {
   
$n=func_num_args();
    if(
$n>0 ) {
       
$rval=func_get_arg(0);
        if( !
is_array($rval) ) {
           
$rval=(array)$rval;
        }
        if(
$n>1 ) {
            for(
$i=1; $i<$n; $i++ ) {
               
$tval=func_get_arg($i);
                if( !
is_array($tval) ) {
                   
$tval=(array)$tval;
                }
               
$rval=array_merge($rval, $tval);
            }
        } else {
           
$rval=array_merge($rval);
        }
    } else {
       
$rval=array_merge();
    }
    return
$rval;
}
?>
ian at fuzzygroove dot com
30-Apr-2008 02:51
I needed a function to interlace two arrays ([a,b,c] + [d,e,f] = [a,d,b,e,c,f]) and came up with the following. This function works for arrays of varying lengths and keeps the keys sequenced properly.

<?php

$a
= array ('a', 'b', 'c');
$b = array ('d', 'e', 'f', 'g', 'h', 'i');

$c = array_interlace ($a, $b);
/*
Array
(
    [0] => a
    [1] => d
    [2] => b
    [3] => e
    [4] => c
    [5] => f
    [6] => g
    [7] => h
    [8] => i
)
*/

function array_interlace ($a, $b)
{
   
$c = array();
   
   
$shorty = (count($a) > count($b)) ? $b : $a;
   
$biggy = (count($a) > count($b)) ? $a : $b;
   
   
$slen = count($shorty);
   
$blen = count($biggy);

    for (
$i = 0; $i < $slen; ++$i){
       
$c[$i * 2] = $a[$i];
       
$c[$i * 2 + 1] = $b[$i];
    }
   
    for (
$i = $slen; $i < $blen; ++$i)
    {
       
$c[] = $biggy[$i];
    }
   
    return
$c;
}
?>
bishop
05-Apr-2008 01:02
The documentation is a touch misleading when it says: "If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way."  Even with two arrays, the resulting array is re-indexed:

[bishop@predator staging]$ cat array_merge.php
<?php
$a
= array (23 => 'Hello', '42' => 'World');
$a = array_merge(array (0 => 'I say, '), $a);
var_dump($a);
?>
[bishop@predator staging]$ php-5.2.5 array_merge.php
array(3) {
  [0]=>
  string(7) "I say, "
  [1]=>
  string(5) "Hello"
  [2]=>
  string(5) "World"
}
[bishop@predator staging]$ php-4.4.7 array_merge.php
array(3) {
  [0]=>
  string(7) "I say, "
  [1]=>
  string(5) "Hello"
  [2]=>
  string(5) "World"
}
no at spam dot com
03-Apr-2008 05:30
@Kevin Campbell:

Yep, be carefull....the docu is misleading....

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

will produce:

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

whereas the `+` operator:

$beginning = 'foo';
$end = array(0 => 'bar');
$result = (array)$beginning + (array)$end;
print_r($result);

will produce:

Array
(
   [0] => foo
)
no_one at nobody dot com
03-Mar-2008 06:31
PHP is wonderfully decides if an array key could be a number, it is a number!  And thus wipes out the key when you array merge.   Just a warning.

$array1['4000'] = 'Grade 1 Widgets';
$array1['4000a'] = 'Grade A Widgets';
$array2['5830'] = 'Grade 1 Thing-a-jigs';
$array2['HW39393'] = 'Some other widget';

var_dump($array1);
var_dump($array2);

//results in...
array(2) {
  [4000]=>
  string(15) "Grade 1 Widgets"
  ["4000a"]=>
  string(15) "Grade A Widgets"
}
array(2) {
  [5830]=>
  string(20) "Grade 1 Thing-a-jigs"
  ["HW39393"]=>
  string(17) "Some other widget"
}

var_dump(array_merge($array1,$array2));
//results in...
array(4) {
  [0]=>
  string(15) "Grade 1 Widgets"
  ["4000a"]=>
  string(15) "Grade A Widgets"
  [1]=>
  string(20) "Grade 1 Thing-a-jigs"
  ["HW39393"]=>
  string(17) "Some other widget"
}
Hayley Watson
04-Nov-2007 10:38
As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.
sam_hunting2004 at yahoo dot com
18-Oct-2007 05:45
Re: Renumbering arrays:

This (from rcarvalhoREMOVECAPS at clix dot pt):

   $a = array_merge($a, null);

does not renumber the array in PHP5. However this:

   $a = array_merge($a, array());

does renumber the $a array in PHP5.

I think that's more clear than the other renumbering proposal, though I don't know about performance:

   $b = implode(" ", $a);
   $a = explode(" ", $b);

Hope this helps...
Kevin Campbell
17-Aug-2007 01:33
The notes in Example 257 above are incorrect. It states:

If you want to completely preserve the arrays and just want to append them to each other, use the + operator

Check the array type page at http://www.php.net/manual/en/language.types.array.php which states differently. Duplicate keys are ignored with the + operator.
clancyhood at gmail dot com
22-Jul-2007 02:52
Similar to Jo I had a problem merging arrays (thanks for that Jo you kicked me out of my debugging slumber) - array_merge does NOT act like array_push, as I had anticipated

<?php

$array
= array('1', 'hello');
array_push($array, 'world');

var_dump($array);

// gives '1', 'hello', 'world'

 
$array = array('1', 'hello');
array_merge($array, array('world'));

// gives '1', 'hello'

$array = array('1', 'hello');
$array = array_merge($array, array('world'));

// gives '1', 'hello', 'world'

?>

hope this helps someone
jyee
27-Jun-2007 02:14
in regards to Joe's problem with arr1 + arr2 versus array_merge(arr1, arr2) - this seems to have been fixed in php 5.2.3

$arr1['foo'] = 'bar';
$arr2['bar'] = 'baz';
$arr3 = $arr1 +$arr2;

print_r($arr3) will produce:
array(
   'foo' => 'bar',
   'bar' => 'baz'
);

I should also note that array_merge() will convert strings of integers into integers for php 5.2.3.  For example:
$arr1['007'] = 'james bond';
$arr2['008'] = 'some other spy';
$arr3 = array_merge($arr1, $arr2);

print_r($arr3) will produce:
array(
   7 => 'james bond',
   8 => 'some other spy'
);

so if you must maintain leading zeros, it's best to use $arr1 + $arr2 instead of array_merge.
Joe at neosource dot com dot au
04-Jun-2007 09:51
I found the "simple" method of adding arrays behaves differently as described in the documentation in PHP v5.2.0-10.

$array1 + $array2 will only combine entries for keys that don't already exist.

Take the following example:

$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = ($ar1 + $ar2);
print_r($ar3);

Result:

Array
(
    [0] => a
    [1] => b
)

Where as:

$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = array_merge($ar1, $ar2);
print_r($ar3);

Result:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Hope this helps someone.
RQuadling at GMail dot com
21-May-2007 03:05
For asteddy at tin dot it and others who are trying to merge arrays and keep the keys, don't forget the simple + operator.

Using the array_merge_keys() function (with a small mod to deal with multiple arguments), provides no difference in output as compared to +.

<?php
$a
= array(-1 => 'minus 1');
$b = array(0 => 'nought');
$c = array(0 => 'nought');
var_export(array_merge_keys($a,$b));
var_export($a + $b);
var_export(array_merge_keys($a,$b,$c));
var_export($a + $b + $c);
?>

results in ...

array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
Marce!
02-Mar-2007 02:21
I have been searching for an in-place merge function, but couldn't find one. This function merges two arrays, but leaves the order untouched.
Here it is for all others that want it:

function inplacemerge($a, $b) {
  $result = array();
  $i = $j = 0;
  if (count($a)==0) { return $b; }
  if (count($b)==0) { return $a; }
  while($i < count($a) && $j < count($b)){
    if ($a[$i] <= $b[$j]) {
      $result[] = $a[$i];
      if ($a[$i]==$b[$j]) { $j++; }
      $i++;
    } else {
      $result[] = $b[$j];
      $j++;
    }
  }
  while ($i<count($a)){
    $result[] = $a[$i];
    $i++;
  }
  while ($j<count($b)){
    $result[] = $b[$j];
    $j++;
  }
  return $result;
}
ahigerd at stratitec dot com
24-Jan-2007 04:06
An earlier comment mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
lcvalentine at gmail dot com
22-Jan-2007 08:23
I recently upgrade from PHP4 to PHP5.  While using PHP4, there was a certain set of information that we filtered into the $_SESSION global at login.  i.e.

$_SESSION = array_merge( $_SESSION, $additional_vals );

This method worked great in PHP4, but not in PHP5.  I can only assume the session immediately invalidated itself.

In fact, my tests to find this bug, led me to find out that all session changes - even those before this action - were lost.

DO NOT USE array_merge() FROM $_SESSION AND TO $_SESSION
asteddy at tin dot it
16-Jan-2007 05:51
Sorry, I forgot to translate the the name of the function when it calls itself. Here is the correct code:
<?
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
    foreach($arr2 as $k=>$v) {
        if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
            $arr1[$k]=$v;
        }
        else { // K EXISTS //
            if (is_array($v)) { // K IS AN ARRAY //
                $arr1[$k]=array_merge_keys($arr1[$k], $arr2[$k]);
            }
        }
    }
    return $arr1;
}
?>
asteddy at tin dot it
15-Jan-2007 04:06
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
    foreach($arr2 as $k=>$v) {
        if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
            $arr1[$k]=$v;
        }
        else { // K EXISTS //
            if (is_array($v)) { // K IS AN ARRAY //
                $arr1[$k]=array_unisci_chiavi($arr1[$k], $arr2[$k]);
            }
        }
    }
    return $arr1;
}
m dot kaczanowski at alianet dot pl
13-Dec-2006 08:47
To: zspencer at zacharyspencer dot com

You forget about code of this function.

<?
function safe_array_merge($a, $b) {
    foreach ($b as $v) {
        $a[] = $v;
    }
    return $a;
}
?>
zspencer at zacharyspencer dot com
09-Nov-2006 06:55
I noticed the lack of a function that will safely merge two arrays without losing data due to duplicate keys but different values.

So I wrote a quicky that would offset duplicate keys and thus preserve their data. of course, this does somewhat mess up association...

<?php
$array1
=array('cats'=>'Murder the beasties!', 'ninjas'=>'Use Ninjas to murder cats!');
$array2=array('cats'=>'Cats are fluffy! Hooray for Cats!', 'ninjas'=>'Ninas are mean cat brutalizers!!!');
$array3=safe_array_merge($array1, $array2);
print_r($array3)
01-Nov-2006 04:47
A more efficient array_merge that preserves keys, truly accepts an arbitrary number of arguments, and saves space on the stack (non recursive):
<?php
function array_merge_keys(){
   
$args = func_get_args();
   
$result = array();
    foreach(
$args as &$array){
        foreach(
$array as $key=>&$value){
           
$result[$key] = $value;
        }
    }
    return
$result;
}
?>
BigueNique at yahoo dot ca
29-Sep-2006 05:10
Needed an quick array_merge clone that preserves the keys:

<?
// function array_join
// merges 2 arrays preserving the keys,
// even if they are numeric (unlike array_merge)
// if 2 keys are identical, the last one overwites
// the existing one, just like array_merge
// merges up to 10 arrays, minimum 2.
function array_join($a1, $a2, $a3=null, $a4=null, $a5=null, $a6=null, $a7=null, $a8=null, $a9=null, $a10=null) {
    $a=array();
    foreach($a1 as $key=>$value) $a[$key]=$value;
    foreach($a2 as $key=>$value) $a[$key]=$value;
    if (is_array($a3)) $a=array_join($a,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$a10);
    return $a;
}
?>
poison
12-Sep-2006 03:45
You can use array_slice() in combination with array_merge() to insert values into an array like this:

<?php
$test
=range(0, 10);
$index=2;
$data="---here---";
$result=array_merge(array_slice($test, 0, $index), array($data), array_slice($test, $index));
var_dump($result);
?>
dercsar at gmail dot com
04-Sep-2006 11:34
array_merge() overwrites ALL numerical indexes. No matter if you have non-numerical indexes or more than just one array.
It reindexes them all. Period.

(Only tried in 4.3.10)
20-Jul-2006 06:45
Whoops!!!  The 2nd posting before this one about the array_merge_alternative1() I made.  Replace part of that code with this one below...

--snip--
     /* 07/20/2006 - Added the if statement to avoid the warning message spitted out by array_unique() function, "Warning: Wrong datatype in array_unique() call"... */
     if ($xyz != 0) {
        $new_array2 = array_unique($new_array1);  /* Work a lot like DISTINCT() in SQL... */
     } else {
        $new_array2 = array();
     }
--snip--

Because the unique_array() unexpectly give a warning message when it's empty...  Sorry about that...
anonyme
20-Jul-2006 04:02
I don't think that the comment on + operator for array in array_merge page, was understandable, this is just a little test to know exactly what's happend.

<?php
//test code for (array)+(array) operator
$a1 = array( '10', '11' , '12' , 'a' => '1a', 'b' => '1b');
$a2 = array( '20', '21' , '22' , 'a' => '2a', 'c' => '2c');

$a = $a1 + $a2;
print_r( $a );
//result: Array ( [0] => 10
//                [1] => 11
//                [2] => 12
//                [a] => 1a
//                [b] => 1b
//                [c] => 2c )

$a = $a2 + $a1;
print_r( $a );
//result: Array ( [0] => 20
//                [1] => 21
//                [2] => 22
//                [a] => 2a
//                [c] => 2c
//                [b] => 1b )

?>
sfletcher at abcoa dot com
19-Jul-2006 07:28
I found that array_merge() didn't work in my case as it should have because I still get duplicate values.  Again, I noticed that the values can be overwritten if the array's key are the same as stated in the manual.

So, I came up with the alternative and it work like a charm.

--snip--
   function array_merge_alternative1() {
      //echo func_num_args();  /* Get the total # of arguements (parameter) that was passed to this function... */
      //print_r(func_get_arg());  /* Get the value that was passed in via arguement/parameter #... in int, double, etc... (I think)... */
      //print_r(func_get_args());  /* Get the value that was passed in via arguement/parameter #... in arrays (I think)... */

     $loop_count1 = func_num_args();
     $junk_array1 = func_get_args();
     $xyz = 0;
    
     for($x=0;$x<$loop_count1;$x++) {
        $array_count1 = count($junk_array1[$x]);

        if ($array_count1 != 0) {
           for($y=0;$y<$array_count1;$y++) {
              $new_array1[$xyz] = $junk_array1[$x][$y];
              $xyz++;
           }
        }
     }

     $new_array2 = array_unique($new_array1);  /* Work a lot like DISTINCT() in SQL... */

     return $new_array2;
   }
--snip--

Cheer...
chris at luethy dot net
13-Jul-2006 03:36
Do not use this to set the $_SESSION variable.

$_SESSION = array_merge( $_SESSION, $another_array );

will break your $_SESSION until the end of the execution of that page.
freed489 at gmail dot com
18-May-2006 06:32
I needed a function to alternatly merge 2 arrays. i.e. $a1 = (a, c, e) and $a2 = (b, d, f), and now $merged = (a, b, c, d, e, f).
Hope it helps...

<?
function alternatly_merge_arrays($array1, $array2){
        $combined_array = array();
    $count = 0;
    for($i = 0; $i < count($array1) + count($array2); $i = $i + 2){
            $combined_array[$i] = $array1[$count];
        $count++;
    }//end for
    $count = 0;
    for($i = 1; $i < count($array1) + count($array2); $i = $i + 2){
        $combined_array[$i] = $array2[$count];
        $count++;
    }//end for
    return $combined_array;
}//end alternate_merge_arrays
?>
j_oaquimsilva at yahoo dot com dot br
16-Jan-2006 11:22
I forgot to comment. This function join two arrays adding first the elements equals in the two arrays, then the values of the first array and at the end the values of the second array.
<?php
function array_merge_sim ($arr1, $arr2) {

              
$i=0;
              
$adid_arrayS = array();
               foreach (
$arr1 as $x) {

                      
$j=0;
                      
$nr1=count($arr1);
                      
$nr2=count($arr2);

                       foreach (
$arr2 as $z) {
                         if(
$x==$z){
                              
array_push($adid_arrayS,$z);
                               if(
$nr2==($j+1)) array_pop($arr2);
                               else
array_splice($arr2, $j,-($nr2-$j-1));
                               if(
$nr1==($i+1)) array_pop($arr1);
                               else
array_splice($arr1, $i,-($nr1-$i-1));
                              
$i--;
                         }else 
$j++;
                       }
              
$i++;
               }

               return
array_merge($adid_arrayS,$arr1,$arr2);

}
?>
seva-php at zend dot com
04-Jan-2006 11:18
Since my comment from 12-Jul-2004 02:42 with <? function array_merge_php4() ?> was deleted and the complex one added by Barpfotenbaer (09-Jul-2005 06:33), - here is the simpler and faster solution:

<?
/* works only with PHP 5 */
function array_merge_php4($array1, $array2) {
    foreach ($args = func_get_args() as &$arg)  {
        $arg = (array)$arg;
    }
    return call_user_func_array('array_merge',$args);
}

?>
hs at nospam dot magnum-plus dot com
30-Dec-2005 12:50
The same result as produced by snookiex_at_gmail_dot_com's function
can be achieved with the 'one-liner'
<?php
$array1
=array(1,2,3);
$array2=array('a','b','c');

$matrix = array_map(null, $array1, $array2);
?>
(see documentation of array_map).
The difference here is, that the shorter array gets filled with empty values.
snookiex_at_gmail_dot_com
10-Dec-2005 04:09
if you have, for instance:

$array1=array(1,2,3);
$array2=array('a','b','c');

but you want a 2x3 matrix like this:
1 a
2 b
3 c

use:
function arrays2matrix($array1,$array2){
        if(sizeof($array1) != sizeof($array2))
                return;
    for($i=0;$i<sizeof($array1);$i++)
        $res[]=array_merge($array1[$i],$array2[$i]);
    return $res;
}
ttsgosadow at gmail dot com
17-Nov-2005 12:17
I was in need of a version of array_merge to add associative arrays without losing duplicate keys. I use the following function:

[code]
function array_add( $array1, $array2 )
{
foreach( $array2 AS $key => $value )
{
    while( array_key_exists( $key, $array1 ) )
        $key .= "_";
    $array1[ $key ] = $value;
}

return $array1;
}
[/code]

In my case the $key is a date I want to sort on, and if I happen to have duplicate dates (users add things on the same timestamp) I lose that entry with array_merge. I can sort on the key without getting big missorts because of the appended '_'.
kaigillmann at gmxpro dot net
02-Nov-2005 01:56
If you need to merge two arrays without having multiple entries, try this:

<?php
function array_fusion($ArrayOne, $ArrayTwo)
{
    return
array_unique(array_merge($ArrayOne, $ArrayTwo));
}
?>
topera at gmail dot com
07-Oct-2005 02:25
<?
/*
Warning: if one variable is not an array, the merged array will
have one more line!
*/

$a = "";

$b[0] = "Brazil";
$b[1] = "China";

$c = array_merge($a, $b);

print_r($c);

?>

This returns:

Array
(
    [0] =>
    [1] => Brazil
    [2] => China
)
__________________________________
Rafael Pereira dos Santos
tbs2tbs at hotmail dot com
31-Aug-2005 09:55
I wanted to share this, it's an small simple script to add things into an array using an loop/routine.
I use an more developed version to sort msessage's on a forum.

<?php

// Make vars ready
   
$a=0;
   
$alltopic = array();

// Start an routine
//    4 is just an example you can use an varible containing
//    the number of rows in an databse for example
   
while ($a < 4)
        {
           
$topic = array($a => "$a");
           
$alltopic = array_merge ($alltopic, $topic);
           
$a++;
        };

// Put it on screen:
   
print_r($alltopic);

?>

outputs this :

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
php at moechofe dot com
20-Jul-2005 02:58
<?php

 
/*
  * array_deep_merge
  *
  * array array_deep_merge ( array array1 [, array array2 [, array ...]] )
  *
  * Like array_merge
  *
  *   array_deep_merge() merges the elements of one or more arrays together so
  * that the values of one are appended to the end of the previous one. It
  * returns the resulting array.
  *   If the input arrays have the same string keys, then the later value for
  * that key will overwrite the previous one. If, however, the arrays contain
  * numeric keys, the later value will not overwrite the original value, but
  * will be appended.
  *   If only one array is given and the array is numerically indexed, the keys
  * get reindexed in a continuous way.
  *
  * Different from array_merge
  *   If string keys have arrays for values, these arrays will merge recursively.
  */
 
function array_deep_merge()
  {
    switch(
func_num_args() )
    {
      case
0 : return false; break;
      case
1 : return func_get_arg(0); break;
      case
2 :
       
$args = func_get_args();
       
$args[2] = array();
        if(
is_array($args[0]) and is_array($args[1]) )
        {
          foreach(
array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key )
          if(
is_string($key) and is_array($args[0][$key]) and is_array($args[1][$key]) )
           
$args[2][$key] = array_deep_merge( $args[0][$key], $args[1][$key] );
          elseif(
is_string($key) and isset($args[0][$key]) and isset($args[1][$key]) )
           
$args[2][$key] = $args[1][$key];
          elseif(
is_integer($key) and isset($args[0][$key]) and isset($args[1][$key]) ) {
           
$args[2][] = $args[0][$key]; $args[2][] = $args[1][$key]; }
          elseif(
is_integer($key) and isset($args[0][$key]) )
           
$args[2][] = $args[0][$key];
          elseif(
is_integer($key) and isset($args[1][$key]) )
           
$args[2][] = $args[1][$key];
          elseif( ! isset(
$args[1][$key]) )
           
$args[2][$key] = $args[0][$key];
          elseif( ! isset(
$args[0][$key]) )
           
$args[2][$key] = $args[1][$key];
          return
$args[2];
        }
        else return
$args[1]; break;
      default :
       
$args = func_get_args();
       
$args[1] = array_deep_merge( $args[0], $args[1] );
       
array_shift( $args );
        return
call_user_func_array( 'array_deep_merge', $args );
        break;
    }
  }

 
/*
  * test
  */
 
$a = array(
   
0,
    array(
0 ),
   
'integer' => 123,
   
'integer456_merge_with_integer444' => 456,
   
'integer789_merge_with_array777' => 789,
   
'array' => array( "string1", "string2" ),
   
'array45_merge_with_array6789' => array( "string4", "string5" ),
   
'arraykeyabc_merge_with_arraykeycd' => array( 'a' => "a", 'b' => "b", 'c' => "c" ),
   
'array0_merge_with_integer3' => array( 0 ),
   
'multiple_merge' => array( 1 ),
  );

 
$b = array(
   
'integer456_merge_with_integer444' => 444,
   
'integer789_merge_with_array777' => array( 7,7,7 ),
   
'array45_merge_with_array6789' => array( "string6", "string7", "string8", "string9" ),
   
'arraykeyabc_merge_with_arraykeycd' => array( 'c' => "ccc", 'd' => "ddd" ),
   
'array0_merge_with_integer3' => 3,
   
'multiple_merge' => array( 2 ),
  );

 
$c = array(
   
'multiple_merge' => array( 3 ),
  );
 
  echo
"<pre>".htmlentities(print_r( array_deep_merge( $a, $b, $c ), true))."</pre>";

?>
ntpt at centrum dot cz
14-Jul-2005 04:44
Old behavior of array_merge can be restored by simple  variable type casting like this

array_merge((array)$foo,(array)$bar);

works good in php 5.1.0 Beta 1, not tested in other versions

seems that empty or not set variables are casted to empty arrays
Barpfotenbaer
09-Jul-2005 07:33
Topic: The modified behavior of array_merge() in PHP5: "array_merge() now only accepts parameters of type array"

A very simple way to simulate the old behavior of PHP4 to merge arrays with non-arrays:

<?php
function array_merge_php4 ()
{
$array["merged"]=array ();
for(
$i=0;$i<func_num_args ();$i++)
  {
 
$array["tmp"]=(
    (
is_array (func_get_arg ($i)))?
    (
func_get_arg ($i)):
    (array (
func_get_arg ($i)))
  );
 
$array["merged"]=array_merge ($array["merged"],$array["tmp"]);
  }
return(
$array["merged"]);
}
?>
herve dot pages at free dot fr
08-Jul-2005 09:37
About the behavior of array_merge() that was modified in PHP5. The above warning says "array_merge() now only accepts parameters of type array". But it doesn't say what happens when array_merge() is given a non array parameter like in:
<?php
  error_reporting
(E_STRICT);
 
$a = array("red","green");
 
$rgb = array_merge($a,"blue");
?>
In fact, the PHP5 version of array_merge() will perfectly accept the "blue" parameter and will return... the NULL value! Be aware that you will get no warning even with the error reporting level set to E_STRICT (which is supposed to catch "forward compatibility" troubles).
arduenn at gmail dot com
06-Jul-2005 08:56
As "rcarvalhoREMOVECAPS at clix dot pt" suggested above,

   $a = array_merge($a, null);

does renumber the $a array. However, this only works with PHP4, not with PHP5. PHP5 users might try the following:

   $b = implode(" ", $a);
   $a = explode(" ", $b);

Hope this helps someone too ;-)
alberto dot pacheco at itesm dot mx
24-May-2005 07:02
To insert an array inside another at a given position

<?php

//Insert at $pos array $items inside array $source
function array_insert($source, $pos, $items)
{
   
$sub1 = array_slice($source, 0, $pos);
   
$sub2 = array_slice($source, $pos);
    return
array_merge($sub1,$items,$sub2);
}

// 2nd alternative (Note: it changes $source)
function array_insert($source, $pos, $items)
{
   
$rest = array_splice($source, $pos);
    return
$source = array_merge($source,$items,$rest);
}

?>
rafmavCHEZlibre_in_france
20-Apr-2005 02:54
Here are a few functions to make a diff between two arrays (or 2 strings, see the example) and merge it back after
<?
function array_diff_both($new,$old)
{
    $del=array_diff_assoc($old,$new);
    $add=array_diff_assoc($new,$old);
    return $diff=array("del"=>$del, "add"=>$add);
}

function array_diff_all($arr_new,$arr_old)
{
    $arr_equ=array_intersect_assoc($arr_new,$arr_old);
    $arr_del=array_diff_assoc($arr_old,$arr_new);
    $arr_add=array_diff_assoc($arr_new,$arr_old);
    return $diff=array("equ"=>$arr_equ, "del"=>$arr_del, "add"=>$arr_add);
}

function array_merge_diff($arr,$diff) {
    $arr=array_merge_replace($arr,$diff["del"]);
    $arr=array_merge_replace($arr,$diff["add"]);
    return $arr;
}
function array_merge_diff_reverse($arr,$diff) {
    $arr=array_merge_replace($arr,$diff["add"]);
    $arr=array_merge_replace($arr,$diff["del"]);
    return $arr;
}
?>
Here is an example:
<?
//calculationg
$new="hello!"; // new string

$old="hrllo!"; // old string with a typo fault

// cast string in array the goodway
// make a cast (array) to a string does not work:
// the entire string is thus considered as one element
// of the array !!
$a_new=str_split($new);
$a_old=str_split($old); // cast string in array

$diff=array_diff_both($a_new,$a_old); // the entire diff

$test=array_merge_diff($a_old,$diff);

$test_reverse=array_merge_diff_reverse($a_new,$diff);

//for output the sample
print "new= $new<br/>old= $old<br/>\$a_new= ";
print_r($a_new);

print "<br/>\$a_old= ";
print_r($a_old);

print "<br/>\$diff=\$a_new-\$a_old";
print "<br/>\$diff= ";
print_r($diff);

print "<br/>\$test=\$a_old+\$diff";
print "<br/>\$test= ";
print_r($test);
print("<br/>".implode($test));

print "<br/>\$test_reverse=\$a_new+\$diff";
print "<br/>\$test_reverse= ";
print_r($test_reverse);
print("<br/>".implode($test_reverse));
?>
En sortie de l'exemple, résultats:

new= hello!
old= hrllo!
$a_new= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
$a_old= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [1] => r ) [add] => Array ( [1] => e ) )
$test=$a_old+$diff
$test= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
hello!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
hrllo!

autre exemple, autre résultat:
new= see you!
old= sea ya!
$a_new= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
$a_old= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [2] => a [5] => a [6] => ! ) [add] => Array ( [2] => e [5] => o [6] => u [7] => ! ) )
$test=$a_old+$diff
$test= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
see you!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! [7] => ! )
sea ya!!
Vinicius Cubas Brand
14-Apr-2005 07:32
The following function merges two arrays taking as parameter an user-defined comparison function:

<?
    function array_merge_custom(&$array1,&$array2,$comparison_func)
    {
        $ret_arr = array();
        foreach ($array1 as $key1 => $element1)
        {
            $has_equal_in_2 = false;
            foreach($array2 as $key2 => $element2)
            {
                if (call_user_func($comparison_func,$element1,$element2))
                {
                    $has_equal_in_2 = true;
                }
            }
            if (!$has_equal_in_2)
            {
                $ret_arr[] = $array1[$key1];
            }
        }
        $ret_arr = array_merge($ret_arr,$array2);
        return $ret_arr;
    }

?>

For instance:

<?

    $a = array(
        array('index' => 'ball', 'blabla' => 0),
        array('index' => 'coconut'),
        array('index' => 'cow'),
        array('index' => 'son'),
        );

    $b = array(
        array('index' => 'phone'),
        array('index' => 'wallet'),
        array('index' => 'ball'),
        array('index' => 'son', 'kabum'=> 1)
        );

    $c = array_merge_custom($a,$b,create_function('$a,$b','return $a[\'index\'] == $b[\'index\'];'));
    print_r($c)
?>

Will produce:

Array
(
    [0] => Array
        (
            [index] => coconut
        )
    [1] => Array
        (
            [index] => cow
        )
    [2] => Array
        (
            [index] => phone
        )
    [3] => Array
        (
            [index] => wallet
        )
    [4] => Array
        (
            [index] => ball
        )
    [5] => Array
        (
            [index] => son
            [kabum] => 1
        )
)
jeff_1089 at yahoo dot com
06-Apr-2005 11:17
Note that casting the array doesn't always work.  For classes, it looks like the class information is lost.  The print_r's below have different behavior.  I would suggest creating an array, rather than casting in most situations. (ie.  do it like $array2).

class myclass {
    private $name;
    private $value;
    function myclass($n, $v) {
        $this->name=$n;
        $this->value=$v;
    }   
}

$itema = new myclass("hair", "orange");
$itemb = new myclass("eyes", "green");
$itemc = new myclass("elbow", "dirty");
$items = array($itemb, $itemc);
print "<BR>";
$array1 = array_merge((array)$itema, $items);
$array2 = array_merge(array($itema), $items);
print "<BR>";
print "<BR>";
print_r($array1);
print "<BR>";
print "<BR>";
print_r($array2);

Array ( [] => orange [0] => myclass Object ( [name:private] => eyes [value:private] => green ) [1] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )

Array ( [0] => myclass Object ( [name:private] => hair [value:private] => orange ) [1] => myclass Object ( [name:private] => eyes [value:private] => green ) [2] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )
lito at eordes dot com
21-Mar-2005 01:54
This is a simple function to merge an array multidimensional:

<?php
 
function multimerge ($array1, $array2) {
    if (
is_array($array2) && count