PHP array_merge() function

Example

Merge two arrays into one array:

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>

Run Example

Definition and Usage

The array_merge() function merges one or more arrays into a single array.

Tip:You can input one or more arrays into the function.

Note:If two or more array elements have the same key name, the last element will overwrite the other elements.

Note:If you only input an array to the array_merge() function and the key name is an integer, then the function will return a new array with integer keys, which are re-indexed starting from 0 (see the example below 1).

Tip:This function is similar to array_merge_recursive() The difference between functions is in handling the case where two or more array elements have the same key name. array_merge_recursive() does not perform key name overlay, but recursively forms an array of values with the same key name.

Syntax

array_merge(array1,array2,array3...)
Parameter Description
array1 Required. Specify an array.
array2 Optional. Specify an array.
array3 Optional. Specify an array.

Technical Details

Return Value: Returns the merged array.
PHP Version: 4+
Update Log: Starting from PHP 5.0, this function only accepts array type parameters.

More Examples

Example 1

Merge two associative arrays into one array:

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>

Run Example

Example 2

Use only one array parameter with integer keys:

<?php
$a=array(3=>"red",4=>"green");
print_r(array_merge($a));
?>

Run Example