Java, J2EE & SOA Certification Training
- 35k Enrolled Learners
- Live Class
One of the common features in most programming languages is Array. Arrays are extremely useful to help us keep information in an organized manner. This article will introduce you to Array Merge In PHP with suitable programmatic demonstration. Following pointers will be covered here,
In PHP, array_merge is a builtin function that is used to merge one or more arrays into a single array. We use this function to merge multiple elements or values all together into a single array which occurs in such a way that the values of one array are appended to the previous array. In an array, if we have the same string key repeated, then the previous value for the key will be overwritten by the next one.
The given code below illustates the above statement:
<pre> <?php $var = array ('p' => 'ashok', 'p' => 'tarun', 'r' =>'charan'); print_r ($var); ?> </pre>
[p] => tarun
[r] => charan
The ‘<pre> tag’ is used to define the text in a pre-formatted manner which preseves the tabs, breaks, text spaces amd other formatting characters. array_merge() takes a list of arrays that needs to be merged which are separated by comma(,) as the parameter and returns a new array with merged arrays passed to the function
array_merge($array1, $array2, $array3, $array4.......$array n);
$array1, $array2, $array3, $array4
are multiple arrays which needs to be merged.
Parameters: List of arrays separated by commas are taken as a parameter by the array_merge() function that is needed to be merged as shown in the syntax. We can pass n number of arrays in the parameter.
Return Value: a new array is returned in which the elements of all arrays are merged together, which are passed in parameters.
 => 89
 => ashok
 => 56
 => 31
 => 65
=> front-end,  => 89,  => ashok, are the list of elements in first array, i.e $var1 and  => 56,  => 31,
=> front-end,  => 65, are the list of elements in $var2.
This brings us to the next bit of this article on Array Merge in PHP
Union operator(+) can also be used for merging 2 arrays but it will not use the keys that are already defined in the previous array. The given code below illustates the above statement:
 => 89
 => ashok
 => 65
Numeric keys will be renumbered. The given code below illustrates the above statement:
<pre> <?php $var1 = array(); $var2 = array(1 => "coder"); $resultarr = array_merge($var1, $var2); print_r($resultarr); ?> </pre>
 => coder
With this we come to an end of this article on Array Merge In PHP, I hope you have learned about the use of arrays in PHP, array_merge function and some of its examples and Union operator which also merges arrays.
If you found this article relevant, check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.
Got a question for us? Please mention it in the comments section of Array Merge In PHP articleand I will get back to you.