Online Tutorials & Training Materials | STechies.com
Register Login

Merge Two Arrays in PHP

|| 0

Merge Two Arrays in PHP
Stechies

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.

Notes:

 

  • 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.

Syntax

array_merge ($array1, $array2, $array3........)

Parameter

This function takes a variable list of arrays (separated by commas), which is to be merged. 

For ex. ($array1, $array2, $array3...)

Note: 

 

  • 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. 

Return Value

Returns the new merged array

Example 

Program 1: Basic Program

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

?> 

Output

Array
(
    [0] => Maruti
    [1] => Hyundai
    [2] => Honda
    [3] => Toyota
    [4] => 400000
    [5] => 450000
    [6] => 500000
    [7] => 900000
)

Program 2: If both arrays have the same keys

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

Output

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

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

Output

Array
(
    [0] => Maruti
    [1] => Honda
)