Array Functions

PHP array_merge() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_merge() function merge one or more arrays into one array.

This function merges the elements of one or more arrays together in such a way that the values of one are appended to the end of the previous one. It returns a new array with merged elements.

The following table summarizes the technical details of this function.

Return Value: Returns the merged array.
Changelog: Since PHP 5.0, this function only accept parameters of type array.
Version: PHP 4+

Syntax

The basic syntax of the array_merge() function is given with:

array_merge(array1, array2, ...)

The following example shows the array_merge() function in action.

<?php
// Sample arrays
$array1 = array("red", "green", "blue");
$array2 = array("apple", "banana");

// Merging the two indexed array
$result = array_merge($array1, $array2);
print_r($result);
?>

Similarly, you can merge two or more associative arrays as shown in the example below:

<?php
// Sample arrays
$array1 = array("a" => "apple", "b" => "ball", "c" => "cat");
$array2 = array("x" => "xylophone", "y" => "yacht", "z" => "zebra");

// Merging the two associative arrays
$result = array_merge($array1, $array2);
print_r($result);
?>

It is also possible to merge indexed and associative array, as shown here:

<?php
// Sample arrays
$array1 = array(4, 6, 12, 18);
$array2 = array("a"=>"apple", "b"=>"ball", "c"=>"cat");

// Merging two indexed arrays
$result = array_merge($array1, $array2);
print_r($result);
?>

Parameters

The array_merge() function accepts the following parameters.

Parameter Description
array1 Optional. Specifies the first array to merge.
array2 Optional. Specifies the second array to merge.
... Optional. Specifies more arrays to merge.

Note: As of PHP version 7.4.0 the array_merge() function can now be called without any parameter. Earlier, at least one parameter has been required.


More Examples

Here're some more examples showing how array_merge() function basically works:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one, as you can see in the following example:

<?php
// Sample arrays
$array1 = array("a"=>"red", "b"=>"green", "c"=>"blue");
$array2 = array("a"=>"apple", "m"=>"mango", "o"=>"orange");

// Merging two associative arrays
$result = array_merge($array1, $array2);
print_r($result);
?>

However, if the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended, as demonstrated in the following example:

<?php
// Sample arrays
$array1 = array(5, 10, 15, 20);
$array2 = array(10, 30, 50, 80);

// Merging two indexed arrays
$result = array_merge($array1, $array2);
print_r($result);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties