27 March 2023

In PHP, you can combine two or more arrays using the + operator or the array_merge() function. While both approaches combine arrays, there are some differences to consider.

Description

The + operator returns a new array containing all the elements from the first array followed by all the elements from the second array, and so on. If the arrays have the same string keys, the values from the second array will overwrite the values from the first array.

array_merge() returns a new array containing all the elements from all the input arrays, with the values from the second array appended to the end of the first array, and so on. If the input arrays have the same string keys, the later value will overwrite the previous value.

Associative Arrays

Source code viewer
  1. $array1 = array('a' => 'apple', 'b' => 'banana');
  2. $array2 = array('b' => 'blueberry', 'c' => 'cherry');
  3.  
  4. $result1 = $array1 + $array2;
  5. print_r($result1);
  6. /*Array
  7. (
  8.   [a] => apple
  9.   [b] => banana
  10.   [c] => cherry
  11. )*/
  12.  
  13. $result2 = array_merge($array1, $array2);
  14. print_r($result2);
  15. /*
  16. Array
  17. (
  18.   [a] => apple
  19.   [b] => blueberry
  20.   [c] => cherry
  21. )*/
Programming Language: PHP

Indexed Arrays

Source code viewer
  1. $array1 = ['one', 'two', 'three'];
  2. $array2 = ['three', 'four', 'five'];
  3.  
  4. $resultPlus = $array1 + $array2;
  5. print_r($resultPlus);
  6. /*Array
  7. (
  8.   [0] => one
  9.   [1] => two
  10.   [2] => three
  11. )*/
  12.  
  13. $resultMerge = array_merge($array1, $array2);
  14. print_r($resultMerge);
  15. /*Array
  16. (
  17.   [0] => one
  18.   [1] => two
  19.   [2] => three
  20.   [3] => three
  21.   [4] => four
  22.   [5] => five
  23. )*/
Programming Language: PHP