In this tutorial we will learn How to merge two or more arrays with PHP, We can use PHP array_merge() function or array_merge_recursive() function to combine two or more arrays into one single array.
Table of Contents
PHP array_merge() function
PHP array_merge() function merges one or more arrays to form a single array.
The resulting array will have values in same order as the arrays defined in the function.
If arrays that are being merged have numbers as their keys then the new combined array will always have keys starting from 0, 1 and so on.
If two or more arrays have common string keys then in the new merged array the value of last array will replace all values that have same key while it's key will remain unchanged.
Example to merge two Indexed arrays.
<?php
$array1=array("HTML","CSS","JavaScript");
$array2=array("jQuery","PHP");
$mergedArray = array_merge($array1,$array2);
print_r($mergedArray);
?>
Combining two Associative arrays with common key of two values.
<?php
$array1=array("a"=>"Red","b"=>"Blue","c"=>"White");
$array2=array("c"=>"Black","d"=>"Orange");
$mergedArray = array_merge($array1,$array2);
print_r($mergedArray);
?>
PHP array_merge_recursive() function
PHP array_merge_recursive() function also combines or merges one or more arrays into a single array.
In array_merge_recursive function if two arrays have a common key, the new array will have an array as a value of that key.
This array with in array will have both values.
Merging two arrays with PHP array_merge_recursive function.
<?php
$array1=array("One","Two");
$array2=array("Three","Four");
print_r(array_merge_recursive($array1,$array2));
?>