Merging arrays means combining two or more arrays into a single array. If this is done manually, then the task becomes difficult. Also, the logic of merging two variables as well as coding different memory allocations using other variables takes a lot of time. In this tutorial, you will learn about PHP array_merge() function for merging two or more arrays.



PHP array_merge() Function

array_merge() function is a built-in function of PHP that is used to merge two or more arrays or several elements into a single array. When a given input array matches its string, the subsequent values ​​of the array override its previous counterpart. When your input arrays contain some numeric keys, the latter value will be appended instead of having its original value acquired. If the array_merge () function takes only one array, the array will be indexed numerically, and the keys will be re-indexed in a continuous fashion. This function can be used if you are using PHP version 4.0 or above.

Elements of arrays are merged in a way where the elements of the second array join at the end of the first array. The syntax of using array_merge() function is:

Syntax:

array_merge(array1, array2, array3, ...)

This function will accept a list of arrays that will be separated by a comma as its parameter. These arrays will be joined together using the array_merge() function as shown in the syntax above. You can add N number of arrays (array_merge($arr_1, $arr_2, ……, $arr_n) separated by comma (','). After this function is executed, it will generate a new array in which all the elements of those arrays that are passed as parameters will remain but under one common array-name.

Here is a simple program showing the use of array_merge() to merge two associative arrays into one array.

Example:

<?php

$arr1=array("g"=>"gold","d"=>"diamond");

$arr2=array("p"=>"platinum","s"=>"silver");

print_r(array_merge($arr1,$arr2));

?>

Program Output:

Array
(
    [g] => gold
    [d] => diamond
    [p] => platinum
    [s] => silver
)

Another example where only one array will be passed as a parameter in array_merge() but with integer keys.

Example:

<?php

$arr =array(2 =>"gold", 6 =>"diamond");

print_r(array_merge($arr));

?>

Program Output:

Array
(
    [0] => gold
    [1] => diamond
)


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram