PHP Function Reference

PHP array_merge() Function



The PHP array_merge() function merges the elements of one or more arrays together such that the values of one are appended to the end of the previous one and returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Syntax

array_merge(arrays)

Parameters

arrays Optional. Specify a variable list of arrays to merge.

Return Value

Returns the resulting array. If called without any arguments, returns an empty array.

Exceptions

NA.

Example:

The example below shows the usage of array_merge() function.

<?php
$Arr1 = array(10, 20, "John" => "London", "Hello");
$Arr2 = array(20, "John" => "Paris", "Marry" => "New York");

//merging Arr1 and Arr2
$Arr3 = array_merge($Arr1, $Arr2);

//displaying the result
print_r($Arr3);
?>

The output of the above code will be:

Array
(
    [0] => 10
    [1] => 20
    [John] => Paris
    [2] => Hello
    [3] => 20
    [Marry] => New York
)

Example:

Consider the example below where an empty array is merged with another array.

<?php
$Arr1 = array();
$Arr2 = array("John"=>"London");

//merging Arr1 and Arr2
$Arr3 = array_merge($Arr1, $Arr2);

//displaying the result
print_r($Arr3);
?>

The output of the above code will be:

Array
(
    [John] => London
)

Example:

Consider one more example where non-array types are merged using this function.

<?php
$str = "John";
$Arr1 = array("Marry"=>"Paris");

//merging str and Arr1
$Arr2 = array_merge((array)$str, $Arr1);

//displaying the result
print_r($Arr2);
?>

The output of the above code will be:

Array
(
    [0] => John
    [Marry] => Paris
)

❮ PHP Array Reference