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
$result1 = $array1 + $array2; /*Array ( [a] => apple [b] => banana [c] => cherry )*/ /* Array ( [a] => apple [b] => blueberry [c] => cherry )*/Programming Language: PHP
Indexed Arrays
Source code viewer
$array1 = ['one', 'two', 'three']; $array2 = ['three', 'four', 'five']; $resultPlus = $array1 + $array2; /*Array ( [0] => one [1] => two [2] => three )*/ /*Array ( [0] => one [1] => two [2] => three [3] => three [4] => four [5] => five )*/Programming Language: PHP