Problem: How to merge two arrays while keeping keys instead of reindexing in PHP?
Solution: This can be achieved in two ways which are by using + operator and by using inbuilt functions.
Method 1: Using + operator.
Example :
<?php $array1 = array( 1 =>'Geeks', 2 =>'For', 3 =>'Geeks' ); $array2 = array( 4 => 'A', 5 => 'Computer', 6 => 'Science', 7 => 'Portal', 8 => 'For', 9 => 'Geeks' ); $merged_array = $array1 + $array2; var_dump ($merged_array); ?> |
chevron_right
filter_none
Output:
array(9) {
[1]=>
string(5) "Geeks"
[2]=>
string(3) "For"
[3]=>
string(5) "Geeks"
[4]=>
string(1) "A"
[5]=>
string(8) "Computer"
[6]=>
string(7) "Science"
[7]=>
string(6) "Portal"
[8]=>
string(3) "For"
[9]=>
string(5) "Geeks"
}
Method 2: Using inbuilt function array_replace() function.
Example :
<?php $array1 = array( 1 =>'Geeks', 2 =>'For', 3 =>'Geeks' ); $array2 = array( 4 => 'A', 5 => 'Computer', 6 => 'Science', 7 => 'Portal', 8 => 'For', 9 => 'Geeks' ); $merged_array = array_replace($array1, $array2); var_dump ($merged_array); ?> |
chevron_right
filter_none
Output:
array(9) {
[1]=>
string(5) "Geeks"
[2]=>
string(3) "For"
[3]=>
string(5) "Geeks"
[4]=>
string(1) "A"
[5]=>
string(8) "Computer"
[6]=>
string(7) "Science"
[7]=>
string(6) "Portal"
[8]=>
string(3) "For"
[9]=>
string(5) "Geeks"
}
Reference :http://php.net/manual/en/function.array-replace.php
Recommended Posts:
- How to merge arrays and preserve the keys in PHP ?
- Minimum time to return array to its original state after given modifications
- PHP | Ds\Map keys() Function
- Remove BST Keys in a given Range
- Windows Shortcut Keys
- Reset keys of array elements using PHP ?
- Introduction to SSH(Secure Shell) Keys
- Node.js | Buffer.keys() Method
- Golang program that uses structs as map keys
- How to iterate over the keys and values with ng-repeat in AngularJS ?
- Python | Remove spaces from dictionary keys
- How to get a list of associative array keys in JavaScript ?
- Handling missing keys in Python dictionaries
- Python | Check if given multiple keys exist in a dictionary
- How to get all property values of a JavaScript Object (without knowing the keys) ?
- PHP | Ds\Map merge() Function
- PHP | Ds\Set merge() Function
- Merge Strategies in Git
- ES6 | Merge Objects
- How to merge two PHP objects?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

