Thursday, September 4, 2025
HomeLanguagesMerge two arrays keeping original keys in PHP

Merge two arrays keeping original keys in PHP

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);
?>


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);
?>


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

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6632 POSTS0 COMMENTS
Nicole Veronica
11800 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11860 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS