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.

PHP
$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

Similar Reads

Using + operator

The + operator preserves the keys of the first array and does not overwrite them with values from the second array. This is useful when you want to keep the original keys and values from the first array and only add new keys from the second array....

Using inbuilt array_replace() function

The array_replace replaces values in the first array with values from the second array when keys are the same....

Using foreach loop

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...