Change language

PHP Combining two or more arrays using array_merge ()

|
Syntax:
array array_merge ($array1, $array2, ......, $arrayn)
Parameters:The array_merge() function takes a comma-separated list of arrays as a parameter to be concatenated, as shown in the syntax. The syntax has n arrays (($array1, $array2, ……, $arrayn) separated by (’, ’). We can pass any number of arrays in the parameter.Returned value:Returns a new array in which the elements of all arrays passed in parameters are concatenated so that the values ​​of one array are added to the end of the previous array.The programs below illustrate the operation of the array_merge ( ) in PHP:
  • Combining two simple arrays : when two more arrays are passed to array_merge(), the values ​​of one array are appended to the end of the previous array. If two elements have the same string keys, the last value will be overridden. Integer keys will be renumbered starting at 0. To combine two arrays, the array_merge() function can be executed as follows: $my_array1 = array ( "size" = > "big" , 2,3); $my_array2 = array ( "a" , "b" , "size" = > "medium" , "shape" = > "circle" , 4); $res = array_merge ( $my_array1 , $my_array2 ); print_r ( $res );  
    ?>
    Output:
    Array ([size] = > medium [0] = > 2 [1] = > 3 [2] = > a [3] = > b [shape] = > circle [4 ] = > 4)
    Note.If the input arrays contain the same string keys, then the later value for this key will overwrite the previous one.
  • Passing a parameter with integer keys : if parameters are passed to the array_merge() function, and the keys of this array parameter are integers, then the keys in the output array will be renumbered starting from 0 and increasing for the next elements by 1. Below programs illustrate this: $my_array = array (1 = > "Geeks" , 3 = > "for" , 2 = > "Geeks" ); $res = array_merge ( $my_array ); print_r ( $res );  
    ?>
    Output:
    Array ([0] = > Geeks [1] = > for [2] = > Geeks)
    $my_array1 = array (0 = > ’ zero_a’ , 2 = > ’two_a’ , 3 = > ’three_a’ ); $my_array2 = array (1 = > ’one_b’ , 3 = > ’three_b’ , 4 = > ’ four_b’ ); $res = array_merge ( $my_array1 , $my_array2 ); print_r ( $res );  
    ?>
    Output:
    Array ([ 0] = > zero_a [1] = > two_a [2] = > three_a [3] = > one_b [4] = > three_b [5] = > four_b)