How to merge two array in php?

Apr 02, 2021 . Admin

Hi Guys,

In this blog,I will explain you how to merge two array in In PHP, array_merge() is a builtin function that is utilized to merge one or more arrays into a single array. We utilize this function to merge multiple elements or values en masse into a single array which occurs in such a way that the values of one array are appended to the precedent array. In an array, if we have the same string key reiterated, then the precedent value for the key will be overwritten by the next one.

array_merge(array1, array2, array3, ...);
Example:1 Note: If two or more array elements have the same key, the last one overrides the others.
    // Indexed array example
  $arr1 = array("Parth","Ramesh","Suresh");
  $arr2 = array("Jaymeen","Pratik","Sanjay");

  $arrMerge = array_merge($arr1,$arr2);

    [0] => Parth
    [1] => Ramesh
    [2] => Suresh
    [3] => Jaymeen
    [4] => Pratik
    [5] => Sanjay

Here, I will give you full example for Merge two associative arrays into one array.

  // Associative Array example
  $array1 = array('key1' => 'test1', 'key2' => 'test2');
  $array2 = array('key3' => 'test3', 'key4' => 'test4');

  $result_Array = array_merge($array1, $array2);

    [key1] => test1
    [key2] => test2
    [key3] => test3
    [key4] => test4

It will help you..