array_merge() joins arrays. String keys from later arrays replace earlier matching string keys, while numeric-keyed values are appended and reindexed.
$first = ['name' => 'Ana', 10, 20];
$second = ['name' => 'Ben', 30];
$result = array_merge($first, $second);
print_r($result);The array union operator (+) behaves differently because it keeps values from the left array when keys already exist.
$result = array_merge($array1, $array2,...);
We will try with an example.
$first=array('a','b','c','d','e');
$second=array('f','g','h');
$result=array_merge($first,$second);
foreach ($result as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
0 -> a
1 -> b
2 -> c
3 -> d
4 -> e
5 -> f
6 -> g
7 -> h
$first=array('a','b','c','d','e');
$second=array('h','d','b','f'); //with some common elements
$result=array_merge($first,$second);
foreach ($result as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
0 -> a
1 -> b
2 -> c
3 -> d
4 -> e
5 -> h
6 -> d
7 -> b
8 -> f
$first=array(1=>'First',2=>'Second',3=>'Third');
$second=array(1=>'fourth',2=>'Fifth',3=>'Sixth');
$result=array_merge($first,$second);
foreach ($result as $key => $val) {
echo "$key -> $val <br>";
}
The output is here.
0 -> First
1 -> Second
2 -> Third
3 -> fourth
4 -> Fifth
5 -> Sixth
Keys are renumbered and incremented starting from 0.
$first=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple');
$second=array('new_fruit1'=> 'Strawberry','new_fruit2'=>'Grapes');
$result=array_merge($first,$second);
foreach ($result as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
Fruits1 -> Banana
Fruits2 -> Mango
Fruits3 -> Apple
new_fruit1 -> Strawberry
new_fruit2 -> Grapes
$first=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple');
$second=array('Fruits1'=> 'Strawberry','Fruits2'=>'Grapes');
$result=array_merge($first,$second);
foreach ($result as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
Fruits1 -> Strawberry
Fruits2 -> Grapes
Fruits3 -> Apple
Keys of the first array will be retained.
$result=$first + $second;
If we use this in place of array_merge() ( in above code ) then the output will be like this
1 -> First
2 -> Second
3 -> Third
Let us change the second array and see the result.
$first=array(1=>'First',2=>'Second',3=>'Third');
$second=array(4=>'fourth',5=>'Fifth',6=>'Sixth');
$result=$first + $second;
foreach ($result as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
1 -> First
2 -> Second
3 -> Third
4 -> fourth
5 -> Fifth
6 -> Sixth
You can read more array Operators.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.