PHP array_merge() Function
PHP array_merge function is an in-built function in PHP, which is used to merge or combine one or multiple arrays into one single array. This function adds elements of one array to the end of the previous array and returns a single resulting array.
- If in case two or more array has similar key elements, than the last key element will override previous similar keys elements.
- User can assign as many arrays he wants to the function
- If only one array is assigned to function and the key of that array are integer, then the array_merge function will return a new array, which will start from 0, and all other integer keys will be increased by 1.
array_merge ($array1, $array2, $array3........)
This function takes a variable list of arrays (separated by commas), which is to be merged.
For ex. ($array1, $array2, $array3…)
- From PHP version 5.0 array_merge function only takes an array type parameter
- From PHP version 7.4 can be executed without any parameter, whereas previously, it was mandatory to pass atleast one parameter.
Returns the new merged array
Program 1: Basic Program
#PHP Program to illustrate the working of array_merge Function of PHP #Simple Program #array - 1 $carsName = array('Maruti','Hyundai','Honda','Toyota'); #array - 2 $carsPrice = array(400000,450000,500000,900000); #$variable to to store the combination of array - 1 and array - 2 $mergedArray = array_merge($carsName,$carsPrice); #printing the output print_r($mergedArray);
Array (  => Maruti  => Hyundai  => Honda  => Toyota  => 400000  => 450000  => 500000  => 900000 )
Program 2: If both arrays have the same keys
#PHP Program to illustrate the working of array_mearge Function of PHP #Advance Program (For if both arrays have the same keys) #array - 1 $carsName=array("a"=>"Maruti","b"=>"Toyota"); #array - 2 $carsPrice=array("c"=>"Hyundai","b"=>"Honda"); #Statement to merge and print the mearged array print_r(array_merge($carsName,$carsPrice));
Array ( [a] => Maruti [b] => Honda [c] => Hyundai )
Program 3: Single array passed with integer keys
If only one array is assigned to function and the keys of that array are integer, then array_merge() function will return a new array, which will start from 0, and all other integer keys will be increased by 1 as shown in the example below.
#PHP Program to illustrate the working of array_mearge Function of PHP #Single array is passed with an integer key $carsName = array(3 => 'Maruti', 6=> 'Honda'); print_r(array_merge($carsName));
Array (  => Maruti  => Honda )