How to Append One Array to the End of Another One in PHP?

Problem:

You have two arrays. You want to add one array to the end of another array.

Solution:

Here, you’ll see two different ways to append two arrays. Each method has its limitation.

Method 1: Using array_merge() function

The built-in function array_merge() can be used to properly append arrays with numeric keys. The elements of the second array will be added at the end of the first array. See the example-

<pre>
<?php
    $language1 = array("C", "C++", "JAVA");
    $language2 = array("PHP", "ASP.NET", "PERL");
    $language = array_merge($language1, $language2);
    print_r($language);
?>
</pre>

[wpdm_file id=29]
Output:

Array
(
  [0] => C
  [1] => C++
  [2] => JAVA
  [3] => PHP
  [4] => ASP.NET
  [5] => PERL
)

Caution: If the both of your input arrays have the same string keys, then the values of the later array will be overwritten the previous one. See the example-

<pre>
<?php
    $language1 = array("one" => "C", "two" => "C++", "three" => "JAVA");
    $language2 = array("one" => "PHP", "two" => "ASP.NET", "three" => "PERL", "four" => "JSP");
    $language = array_merge($language1, $language2);
    print_r($language);
?>
</pre>

[wpdm_file id=30]

Output:

Array
(
  [one] => PHP
  [two] => ASP.NET
  [three] => PERL
  [four] => JSP
)

Recommendation: if the input arrays have numeric keys, use this method to append two arrays without overwriting any element.

Method 2: Using + operator

The + operator(array union operator) can also be used to append two arrays.

If your arrays have different numeric or string keys, you can use + operator to properly append array elements without overwritten any value.

<pre>
<?php
    $language1 = array( 0=> "C", 1=> "C++", 2=> "JAVA");
    $language2 = array( 3=> "PHP", 4=> "ASP.NET", 5=> "PERL");
    $language = $language1 + $language2;
    print_r($language);
?>
</pre>

[wpdm_file id=31]
Output:

Array
(
  [0] => C
  [1] => C++
  [2] => JAVA
  [3] => PHP
  [4] => ASP.NET
  [5] => PERL
)

Caution: Regardless of the numeric or string key, the value of the previous array will be overwritten the later one if both arrays have a same key. See an example of different numeric keys-

<pre>
<?php
    $language1 = array("C", "C++", "JAVA");
    $language2 = array("PHP", "ASP.NET", "PERL");
    $language = $language1 + $language2;
    print_r($language);
?>
</pre>

[wpdm_file id=32]
Output:

Array
(
  [0] => C
  [1] => C++
  [2] => JAVA
)

Recommendation: If the arrays you want to append have different string keys, you can choose either array_merge() or the + operator to append arrays properly.