PHP array_merge()
Function
Complete PHP Array Reference Manual
Example
Merge two arrays into one:
<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
Definition and Usage
The array_merge()
function is used to merge 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, the last element will overwrite the others.
Note: If you only input one array into the array_merge()
function and the keys are integers, the function will return a new array with integer keys, re-indexed starting from 0 (see Example 1 below).
Tip: The difference between this function and the array_merge_recursive()
function is how they handle elements with the same key. array_merge_recursive()
does not overwrite keys; instead, it recursively combines values with the same key into an array.
Syntax
Parameter | Description |
---|---|
array1 | Required. Specifies the array. |
array2 | Optional. Specifies the array. |
array3 | Optional. Specifies the array. |
Technical Details
Return Value: | Returns the merged array. |
---|---|
PHP Version: | 4+ |
--- | --- |
Changelog: | As of PHP 5.0, the function only accepts parameters of type array. |
--- | --- |
More Examples
Example 1
Using only one parameter with integer keys:
<?php
$a=array(3=>"red",4=>"green");
print_r(array_merge($a));
?>