PHP Array Merge

PHP Array Merge

PHP Array Merge is used to Merge one or more arrays, array_merge takes two or more arguments, first argument is the array and second argument is the array to merge. If two or more array elements have the same key, the last one overrides the others. If you passing only one array to the array_merge() function, and the keys are integers, the output will be a new array with integer keys starting at 0 and increases by 1 for each value.

Syntax of an PHP Array Merge Function

Basic syntax of an array Merge function, $array1 is the primary array to merge and it is mandatory. $merge1 & arrays to merge with first array.

[php] array_merge ( $array1 , $merge1, $merge2 )

Example code snippet for PHP Array Merge Function

Below simple example code for merging two arrays using array_merge php function.

[php] <?php
$array1 = array("id1" => "value1");

$array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");

$array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);

echo ‘<pre>’;
echo ‘</pre>’;

Output of array3 will be

If two or more array elements have the same key, the last one overrides the others.

Example code snippet for elements override in an array.

[php] <?php

And the output array after overriding b element. From this example you can understand that b element overridden by second array value. First array b element value is “orange” and second array b element value is “strawberries”

Final example code if you are passing one array, then the output will be same array with keys starting from zero and increases by one.

[php] <?php
[/php] Output array will be like below. Here same array is rearranged with new keys. Starting from zero increases by one. that means keys will be 0,1,2,3,4,5…. so on.

If you have any problem while using array_merge php function, let me know using below comment form.

Vivek Vengala

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: