The array_merge Function
The array_merge
function merges two or
more arrays together. If the arrays being merged
contain the same keys - only one such element will remain.
If you need to keep all elements with the same
keys - use the function array_merge_recursive
.
Syntax
array_merge(array ...$arrays): array
Example
Let's merge two arrays together:
<?php
$arr1 = ['a', 'b', 'c', 'd', 'e'];
$arr2 = [1, 2, 3, 4, 5];
$res = array_merge($arr1, $arr2);
var_dump($res);
?>
Code execution result:
['a', 'b', 'c', 'd', 'e', 1, 2, 3, 4, 5]
Example
Let's merge three arrays together:
<?php
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$arr3 = [7, 8, 9];
$res = array_merge($arr1, $arr2, $arr3);
var_dump($res);
?>
Code execution result:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
See Also
-
the function
array_merge_recursive
,
which also merges arrays -
the function
array_combine
,
which merges two arrays into one associative array