PHP combine two associative arrays into one array











up vote
55
down vote

favorite
13












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










share|improve this question




















  • 5




    Sounds like you're probably just looking for array_merge.
    – Corbin
    Nov 1 '12 at 2: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 at 19:49

















up vote
55
down vote

favorite
13












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










share|improve this question




















  • 5




    Sounds like you're probably just looking for array_merge.
    – Corbin
    Nov 1 '12 at 2: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 at 19:49















up vote
55
down vote

favorite
13









up vote
55
down vote

favorite
13






13





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










share|improve this question















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







php arrays multidimensional-array associative-array






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 1 '12 at 2:59

























asked Nov 1 '12 at 2:45









jsteinmann

2,09121119




2,09121119








  • 5




    Sounds like you're probably just looking for array_merge.
    – Corbin
    Nov 1 '12 at 2: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 at 19:49
















  • 5




    Sounds like you're probably just looking for array_merge.
    – Corbin
    Nov 1 '12 at 2: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 at 19:49










5




5




Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2:47




Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2: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 at 19:49






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 at 19:49














7 Answers
7






active

oldest

votes

















up vote
87
down vote



accepted










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





share|improve this answer



















  • 5




    What is benefit of array_merge over using the operator?
    – jsteinmann
    Nov 1 '12 at 3:01






  • 26




    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 1 '12 at 3:04








  • 10




    It should also be noted that array_merge will return NULL if any of the arguments are NULL.
    – SeanWM
    Mar 6 '14 at 19:07






  • 2




    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 8 '17 at 4:35










  • @user2850305 using the + operator will do the trick
    – Benjamin
    Feb 26 at 8:25


















up vote
20
down vote













Check out array_merge().



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





share|improve this answer

















  • 19




    @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
    – Brad
    Jun 4 '15 at 14:25






  • 2




    @SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
    – Gaurav Pangam
    Mar 7 '17 at 6:34


















up vote
5
down vote













Another option is array_replace, where an original array is modified by other arrays:




  • Same keys will cause subsequent values to overrite the original array

  • New keys on subsequent arrays will be created on the original array


This means that the key => value association is preserved and no duplicate keys are inserted.






share|improve this answer























  • This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
    – Dmitry Belyaev
    Mar 23 '17 at 23:03


















up vote
2
down vote













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





share|improve this answer




























    up vote
    0
    down vote













    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.






    share|improve this answer




























      up vote
      0
      down vote













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





      share|improve this answer






























        up vote
        0
        down vote













                $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






        share|improve this answer





















          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13170230%2fphp-combine-two-associative-arrays-into-one-array%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          87
          down vote



          accepted










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





          share|improve this answer



















          • 5




            What is benefit of array_merge over using the operator?
            – jsteinmann
            Nov 1 '12 at 3:01






          • 26




            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 1 '12 at 3:04








          • 10




            It should also be noted that array_merge will return NULL if any of the arguments are NULL.
            – SeanWM
            Mar 6 '14 at 19:07






          • 2




            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 8 '17 at 4:35










          • @user2850305 using the + operator will do the trick
            – Benjamin
            Feb 26 at 8:25















          up vote
          87
          down vote



          accepted










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





          share|improve this answer



















          • 5




            What is benefit of array_merge over using the operator?
            – jsteinmann
            Nov 1 '12 at 3:01






          • 26




            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 1 '12 at 3:04








          • 10




            It should also be noted that array_merge will return NULL if any of the arguments are NULL.
            – SeanWM
            Mar 6 '14 at 19:07






          • 2




            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 8 '17 at 4:35










          • @user2850305 using the + operator will do the trick
            – Benjamin
            Feb 26 at 8:25













          up vote
          87
          down vote



          accepted







          up vote
          87
          down vote



          accepted






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





          share|improve this answer














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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 at 19:41









          Mohamad Hamouday

          32748




          32748










          answered Nov 1 '12 at 2:50









          Samuel Cook

          13.2k43650




          13.2k43650








          • 5




            What is benefit of array_merge over using the operator?
            – jsteinmann
            Nov 1 '12 at 3:01






          • 26




            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 1 '12 at 3:04








          • 10




            It should also be noted that array_merge will return NULL if any of the arguments are NULL.
            – SeanWM
            Mar 6 '14 at 19:07






          • 2




            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 8 '17 at 4:35










          • @user2850305 using the + operator will do the trick
            – Benjamin
            Feb 26 at 8:25














          • 5




            What is benefit of array_merge over using the operator?
            – jsteinmann
            Nov 1 '12 at 3:01






          • 26




            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 1 '12 at 3:04








          • 10




            It should also be noted that array_merge will return NULL if any of the arguments are NULL.
            – SeanWM
            Mar 6 '14 at 19:07






          • 2




            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 8 '17 at 4:35










          • @user2850305 using the + operator will do the trick
            – Benjamin
            Feb 26 at 8:25








          5




          5




          What is benefit of array_merge over using the operator?
          – jsteinmann
          Nov 1 '12 at 3:01




          What is benefit of array_merge over using the operator?
          – jsteinmann
          Nov 1 '12 at 3:01




          26




          26




          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 1 '12 at 3:04






          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 1 '12 at 3:04






          10




          10




          It should also be noted that array_merge will return NULL if any of the arguments are NULL.
          – SeanWM
          Mar 6 '14 at 19:07




          It should also be noted that array_merge will return NULL if any of the arguments are NULL.
          – SeanWM
          Mar 6 '14 at 19:07




          2




          2




          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 8 '17 at 4:35




          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 8 '17 at 4:35












          @user2850305 using the + operator will do the trick
          – Benjamin
          Feb 26 at 8:25




          @user2850305 using the + operator will do the trick
          – Benjamin
          Feb 26 at 8:25












          up vote
          20
          down vote













          Check out array_merge().



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





          share|improve this answer

















          • 19




            @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
            – Brad
            Jun 4 '15 at 14:25






          • 2




            @SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
            – Gaurav Pangam
            Mar 7 '17 at 6:34















          up vote
          20
          down vote













          Check out array_merge().



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





          share|improve this answer

















          • 19




            @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
            – Brad
            Jun 4 '15 at 14:25






          • 2




            @SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
            – Gaurav Pangam
            Mar 7 '17 at 6:34













          up vote
          20
          down vote










          up vote
          20
          down vote









          Check out array_merge().



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





          share|improve this answer












          Check out array_merge().



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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 1 '12 at 2:47









          Brad

          113k26226386




          113k26226386








          • 19




            @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
            – Brad
            Jun 4 '15 at 14:25






          • 2




            @SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
            – Gaurav Pangam
            Mar 7 '17 at 6:34














          • 19




            @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
            – Brad
            Jun 4 '15 at 14:25






          • 2




            @SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
            – Gaurav Pangam
            Mar 7 '17 at 6:34








          19




          19




          @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
          – Brad
          Jun 4 '15 at 14:25




          @SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
          – Brad
          Jun 4 '15 at 14:25




          2




          2




          @SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
          – Gaurav Pangam
          Mar 7 '17 at 6:34




          @SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
          – Gaurav Pangam
          Mar 7 '17 at 6:34










          up vote
          5
          down vote













          Another option is array_replace, where an original array is modified by other arrays:




          • Same keys will cause subsequent values to overrite the original array

          • New keys on subsequent arrays will be created on the original array


          This means that the key => value association is preserved and no duplicate keys are inserted.






          share|improve this answer























          • This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
            – Dmitry Belyaev
            Mar 23 '17 at 23:03















          up vote
          5
          down vote













          Another option is array_replace, where an original array is modified by other arrays:




          • Same keys will cause subsequent values to overrite the original array

          • New keys on subsequent arrays will be created on the original array


          This means that the key => value association is preserved and no duplicate keys are inserted.






          share|improve this answer























          • This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
            – Dmitry Belyaev
            Mar 23 '17 at 23:03













          up vote
          5
          down vote










          up vote
          5
          down vote









          Another option is array_replace, where an original array is modified by other arrays:




          • Same keys will cause subsequent values to overrite the original array

          • New keys on subsequent arrays will be created on the original array


          This means that the key => value association is preserved and no duplicate keys are inserted.






          share|improve this answer














          Another option is array_replace, where an original array is modified by other arrays:




          • Same keys will cause subsequent values to overrite the original array

          • New keys on subsequent arrays will be created on the original array


          This means that the key => value association is preserved and no duplicate keys are inserted.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 24 '17 at 14:39

























          answered Jan 27 '17 at 19:33









          wranvaud

          7171014




          7171014












          • This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
            – Dmitry Belyaev
            Mar 23 '17 at 23:03


















          • This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
            – Dmitry Belyaev
            Mar 23 '17 at 23:03
















          This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
          – Dmitry Belyaev
          Mar 23 '17 at 23:03




          This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
          – Dmitry Belyaev
          Mar 23 '17 at 23:03










          up vote
          2
          down vote













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





          share|improve this answer

























            up vote
            2
            down vote













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





            share|improve this answer























              up vote
              2
              down vote










              up vote
              2
              down vote









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





              share|improve this answer












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






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 29 '15 at 10:01









              xgretsch

              801912




              801912






















                  up vote
                  0
                  down vote













                  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.






                  share|improve this answer

























                    up vote
                    0
                    down vote













                    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.






                    share|improve this answer























                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      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.






                      share|improve this answer












                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 20 '17 at 2:41









                      Kray

                      402620




                      402620






















                          up vote
                          0
                          down vote













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





                          share|improve this answer



























                            up vote
                            0
                            down vote













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





                            share|improve this answer

























                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









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





                              share|improve this answer














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






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 11 at 6:10

























                              answered Apr 10 at 17:51









                              JohnPan

                              574315




                              574315






















                                  up vote
                                  0
                                  down vote













                                          $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






                                  share|improve this answer

























                                    up vote
                                    0
                                    down vote













                                            $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






                                    share|improve this answer























                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                              $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






                                      share|improve this answer












                                              $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







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jun 6 at 3:41









                                      tom10271

                                      1,17731831




                                      1,17731831






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13170230%2fphp-combine-two-associative-arrays-into-one-array%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Berounka

                                          Sphinx de Gizeh

                                          Different font size/position of beamer's navigation symbols template's content depending on regular/plain...