How to merge two or more arrays in PHP?
Use the array_merge() function to merge two or more arrays into one new array. You can also use the + operator, but it works in a different way.
<?php
$a = [1, 2];
$b = [3, 4];
$c = [5, 6];
print_r(array_merge($a, $b, $c));
?>
Output:
Tutorials Class - Output Window
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
array_merge() vs + operator. When two arrays have the same string key, array_merge() keeps the later value, but the + operator keeps the first value.
<?php
$x = ["a" => "Apple", "b" => "Banana"];
$y = ["b" => "Blueberry", "c" => "Cherry"];
print_r(array_merge($x, $y));
print_r($x + $y);
?>
Output:
Tutorials Class - Output Window
Array
(
[a] => Apple
[b] => Blueberry
[c] => Cherry
)
Array
(
[a] => Apple
[b] => Banana
[c] => Cherry
)
For numeric keys, array_merge() renumbers the keys from 0, while + keeps the keys and skips the ones that already exist. From PHP 7.4 you can also merge with the spread operator, like [...$a, ...$b].
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |