How to use inbuilt array_replace() function In PHP
The array_replace replaces values in the first array with values from the second array when keys are the same.
Example: This example shows the use of the above-explained approach.
<?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);
?>
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) "P...
Merge two arrays keeping original keys in PHP
Merging two arrays in PHP while preserving the original keys can be done using the array_merge or array_replace functions, depending on the desired behavior.
Below are the methods to merge two arrays while keeping the original keys in PHP:
Table of Content
- Using + operator
- Using inbuilt array_replace() function
- Using foreach loop