Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between array_merge and array + array in PHP?
In PHP, both array_merge() and the + operator can combine arrays, but they handle duplicate keys differently. The + operator preserves values from the left array when keys conflict, while array_merge() overwrites duplicate string keys with values from the right array.
Using Array + Operator
The + operator keeps the original values when duplicate keys exist −
<?php
$arr1 = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
$arr2 = array("t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125");
var_dump($arr1 + $arr2);
?>
array(8) {
["p"]=>
string(3) "150"
["q"]=>
string(3) "100"
["r"]=>
string(3) "120"
["s"]=>
string(3) "110"
["t"]=>
string(3) "115"
["u"]=>
string(3) "103"
["v"]=>
string(3) "105"
["w"]=>
string(3) "125"
}
Using array_merge()
The array_merge() function combines arrays and overwrites duplicate string keys −
<?php
$arr1 = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
$arr2 = array("t"=>"115", "u"=>"110", "v"=>"105", "w"=>"100");
var_dump(array_merge($arr1, $arr2));
?>
array(8) {
["p"]=>
string(3) "150"
["q"]=>
string(3) "100"
["r"]=>
string(3) "120"
["s"]=>
string(3) "110"
["t"]=>
string(3) "115"
["u"]=>
string(3) "110"
["v"]=>
string(3) "105"
["w"]=>
string(3) "100"
}
Key Difference with Duplicate Keys
Here's an example showing how they handle duplicate keys differently −
<?php
$arr1 = array("a" => "first", "b" => "second");
$arr2 = array("b" => "overwrite", "c" => "third");
echo "Using + operator:
";
print_r($arr1 + $arr2);
echo "\nUsing array_merge():
";
print_r(array_merge($arr1, $arr2));
?>
Using + operator:
Array
(
[a] => first
[b] => second
[c] => third
)
Using array_merge():
Array
(
[a] => first
[b] => overwrite
[c] => third
)
Conclusion
Use the + operator when you want to preserve original values for duplicate keys, and array_merge() when you want later values to overwrite earlier ones. Both methods handle numeric keys differently by reindexing them.
