Friday, June 12, 2026
HomeLanguagesHow to merge arrays and preserve the keys in PHP ?

How to merge arrays and preserve the keys in PHP ?

Arrays in PHP are created using array() function. Arrays are variable that can hold more than one values at a time. There are three types of arrays:

  1. Indexed Arrays
  2. Associative Arrays
  3. Multidimensional Arrays

Each and every value in an array has a name or identity attached to it used to access that element called keys.

To merge the two arrays array_merge() function works fine but it does not preserve the keys. Instead array_replace() function helps to merge two arrays while preserving their key.

Program 1: This example using array_replace() function to merge two arrays and preserve the keys.




<?php
  
// Create first associative array
$array1 = array(
    1 => 'Welcome',
    2 => 'To'
);
  
// Create second associative array
$array2 = array(
    3 => 'Geeks',
    4 => 'For',
    5 => 'Geeks'
);
  
// Use array_replace() function to
// merge the two array while
// preserving the keys
print_r(array_replace($array1, $array2));
?>


Output:

Array
(
    [1] => Welcome
    [2] => To
    [3] => Geeks
    [4] => For
    [5] => Geeks
)

Program 1: This example using array_replace_recursive() function to merge two arrays and preserve the keys.




<?php
  
// Create first associative array
$array1 = array(
    1 => 'Welcome',
    2 => 'To'
);
  
// Create second associative array
$array2 = array(
    3 => 'Geeks',
    4 => 'For',
    5 => 'Geeks'
);
  
// Use array_replace() function to
// merge the two array while
// preserving the keys
print_r(array_replace_recursive($array1, $array2));
?>


Output:

Array
(
    [1] => Welcome
    [2] => To
    [3] => Geeks
    [4] => For
    [5] => Geeks
)
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS