How to merge two or more arrays in PHP

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.

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));
?>

Demo

How To Remove Empty Array Elements with PHP How To Remove Common Values from two Arrays with PHP How To Find sum of array values with PHP How To Shuffle array Values in PHP How to Remove Duplicate Values from an array with PHP PHP Sort Associative array by Key PHP Sort Associative array by Value Sort array in numerical order with PHP Sort array in alphabetical order with PHP Sort array in descending order PHP Sort array in ascending order in PHP How to merge two or more arrays in PHP Add elements to the end of an array in PHP Add elements to the start of an array in PHP PHP Remove First Element from an Array PHP Remove Last Element from an Array Check if Key Exists in array PHP Check if Value exists in array PHP How to reverse an array in PHP PHP Print array line by line PHP Echo array values using foreach loop Count array values in PHP PHP Count How Many Times Word appears in String How to Reverse a String with PHP Check if Variable is Null in PHP