Merge Arrays in PHP - array_merge()

PHP Array Functions

The function array_merge() merges the elements of two or more arrays together. The values are appended to the end of the previous array. It returns the resulting array.

String Keys

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

$array1 = ['a' => 'apple', 'b' => 'banana']; 
$array2 = ['b' => 'blueberry', 'c' => 'cherry'];

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

Both $array1 and $array2 have a key b. When the arrays are merged, the value 'blueberry' from $array2 overwrites the value 'banana' from $array1 for the key b.

Numeric Keys

If the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

$fruits1 = ['apple', 'banana', 'orange'];
$fruits2 = ['mango', 'grape'];

$merged_fruits = array_merge($fruits1, $fruits2);

The resulting array contains all the elements from both arrays.