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
Merge two arrays keeping original keys in PHP
In PHP, you can merge two arrays while preserving their original keys using the array union operator (+). This operator combines arrays by keeping all unique keys from both arrays, with values from the left array taking precedence when duplicate keys exist.
Syntax
The basic syntax for merging arrays with original keys is −
$result = $array1 + $array2;
Example 1: Merging Arrays with Different Keys
Here's how to merge two associative arrays with unique keys −
<?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"
}
Example 2: Merging with Empty Array
When one array is empty, the union operator simply returns the non-empty array −
<?php
$arr1 = array();
$arr2 = array("a" => "Jacob");
var_dump($arr1 + $arr2);
?>
array(1) {
["a"]=>
string(5) "Jacob"
}
Example 3: Handling Duplicate Keys
When arrays have duplicate keys, values from the left array take precedence −
<?php
$arr1 = array("name" => "John", "age" => 25);
$arr2 = array("name" => "Jane", "city" => "New York");
var_dump($arr1 + $arr2);
?>
array(3) {
["name"]=>
string(4) "John"
["age"]=>
int(25)
["city"]=>
string(8) "New York"
}
Key Points
- The
+operator preserves original keys from both arrays - Values from the left array override duplicate keys
- Order matters:
$arr1 + $arr2differs from$arr2 + $arr1 - Unlike
array_merge(), the union operator maintains key associations
Conclusion
The array union operator (+) is the simplest method to merge arrays while preserving original keys. It's particularly useful when you need to combine configuration arrays or maintain key-value relationships during array operations.
