88
$array1 = array("$name1" => "$id1");

$array2 = array("$name2" => "$id2", "$name3" => "$id3");

I need a new array combining all together, i.e. it would be

$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3");

What is the best way to do this?

Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?

jsteinmann
  • 3,494
  • 2
  • 15
  • 20
  • 5
    Sounds like you're probably just looking for array_merge. – Corbin Nov 01 '12 at 02:47
  • I think the best way, if you know the keys are all different, is to use the += operator: $array1 += $array2; This appends all the elements of $array2 to the end of $array1. – David Spector Nov 10 '18 at 19:49

7 Answers7

133

array_merge() is more efficient but there are a couple of options:

$array1 = array("id1" => "value1");

$array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");

$array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);
$array4 = $array1 + $array2;

echo '<pre>';
var_dump($array3);
var_dump($array4);
echo '</pre>';


// Results:
    array(4) {
      ["id1"]=>
      string(6) "value1"
      ["id2"]=>
      string(6) "value2"
      ["id3"]=>
      string(6) "value3"
      ["id4"]=>
      string(6) "value4"
    }
    array(4) {
      ["id1"]=>
      string(6) "value1"
      ["id2"]=>
      string(6) "value2"
      ["id3"]=>
      string(6) "value3"
      ["id4"]=>
      string(6) "value4"
    }
Mohamad Hamouday
  • 1,024
  • 14
  • 17
Samuel Cook
  • 15,511
  • 6
  • 43
  • 58
  • 7
    What is benefit of array_merge over using the operator? – jsteinmann Nov 01 '12 at 03:01
  • 38
    Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): 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 all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero. – Samuel Cook Nov 01 '12 at 03:04
  • 13
    It should also be noted that `array_merge` will return NULL if any of the arguments are NULL. – SeanWM Mar 06 '14 at 19:07
  • 4
    If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do. – user2850305 Dec 08 '17 at 04:35
24

Check out array_merge().

$array3 = array_merge($array1, $array2);
Brad
  • 146,404
  • 44
  • 300
  • 476
  • 22
    @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer. – Brad Jun 04 '15 at 14:25
11

There is also array_replace, where an original array is modified by other arrays preserving the key => value association without creating duplicate keys.

  • Same keys on other arrays will cause values to overwrite the original array
  • New keys on other arrays will be created on the original array
wranvaud
  • 933
  • 13
  • 18
  • 1
    This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes). – Dmitry Mar 23 '17 at 23:03
3

I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:

/**
 * Merge two arrays - but if one is blank or not an array, return the other.
 * @param $a array First array, into which the second array will be merged
 * @param $b array Second array, with the data to be merged
 * @param $unique boolean If true, remove duplicate values before returning
 */
function arrayMerge(&$a, $b, $unique = false) {
    if (empty($b)) {
        return;  // No changes to be made to $a
    }
    if (empty($a)) {
        $a = $b;
        return;
    }
    $a = array_merge($a, $b);
    if ($unique) {
        $a = array_unique($a);
    }
}
xgretsch
  • 1,123
  • 12
  • 14
2
        $array = array(
            22 => true,
            25 => true,
            34 => true,
            35 => true,
        );

        print_r(
            array_replace($array, [
                22 => true,
                42 => true,
            ])
        );

        print_r(
            array_merge($array, [
                22 => true,
                42 => true,
            ])
        );

If it is numeric but not sequential associative array, you need to use array_replace

tom10271
  • 3,030
  • 4
  • 25
  • 42
0

I stumbled upon this question trying to identify a clean way to join two assoc arrays.

I was trying to join two different tables that didn't have relationships to each other.

This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge() +1 to him.

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
        $ResidentialData = $pdo->prepare($sql);
        $ResidentialData->execute(array($lapi));
        $ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
        $CommercialData = $pdo->prepare($sql);
        $CommercialData->execute(array($lapi));
        $CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);

        $Prospects = array_merge($ResidentialProspects,$CommercialProspects);
        echo '<pre>';
        var_dump($Prospects);
        echo '</pre>';

Maybe this will help someone else out.

lzoesch
  • 1,113
  • 2
  • 14
  • 29
0

UPDATE Just a quick note, as I can see this looks really stupid, and it has no good use with pure PHP because the array_merge just works there. BUT try it with the PHP MongoDB driver before you rush to downvote. That dude WILL add indexes for whatever reason, and WILL ruin the merged object. With my naïve little function, the merge comes out exactly the way it was supposed to with a traditional array_merge.


I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge, array_replace nor array_push worked. I had a bit complex structure of objects wrapped as arrays in array:

$a = [
 ["a" => [1, "a2"]],
 ["b" => ["b1", 2]]
];
$t = [
 ["c" => ["c1", "c2"]],
 ["b" => ["b1", 2]]
];

And I needed to merge them keeping the same structure like this:

$merged = [
 ["a" => [1, "a2"]],
 ["b" => ["b1", 2]],
 ["c" => ["c1", "c2"]],
 ["b" => ["b1", 2]]
];

The best solution I came up with was this:

public static function glueArrays($arr1, $arr2) {
    // merges TWO (2) arrays without adding indexing. 
    $myArr = $arr1;
    foreach ($arr2 as $arrayItem) {
        $myArr[] = $arrayItem;
    }
    return $myArr;
}
JohnPan
  • 885
  • 7
  • 19