How to use foreach loop In PHP
To merge two arrays while preserving original keys using a foreach loop in PHP, iterate through the second array and add each key-value pair to the first array. This way, the original keys from both arrays are maintained in the merged array
Example: This example shows the use of the above-explained approach.
$array1 = ['a' => 'Apple', 'b' => 'Banana'];
$array2 = ['c' => 'Cherry', 'd' => 'Date'];
foreach($array2 as $key => $value) {
$array1[$key] = $value;
}
print_r($array1);
// Output: Array ( [a] => Apple [b] => Banana [c] => Cherry [d] => Date )
Output
$array1 = ['a' => 'Apple', 'b' => 'Banana']; $array2 = ['c' => 'Cherry', 'd' => 'Date']; foreach($array2 as $key => $value) { $array1[$key] = $value; } print_r($array1); // Output: Array ( [a] => ...
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