PHP array_merge() function

P
PHP array_map() function
PHP array_merge_recursive() function

The array_merge merges/combine one or more arrays into one array.

Note: If the two or more arrays to be merged contain the same key, it is overridden by the last array key.

What is the syntax of the array_merge function?

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

Parameter Values

ParameterDescription
array1Specify the array to be merged – Required
array2 Specify the array to be merged – Optional
array3,… Specify the array to be merged – Optional
array_merge function in PHP

Examples of array_merge function

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

In the above example, we merge two indexed arrays into one array using the array_merge function.

<?php
$a1=array("a"=>"1","b"=>"2");
$a2=array("c"=>"4","a"=>"3");
print_r(array_merge($a1,$a2));
?>

In the above example, we merge two associative arrays into one array using the array_merge function. Note in the above example that we have the key “a” in both array 1 and array 2. The resultant array will contain the last array value that is “a” => 3.

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

In the above array, note that there is only one array given to the array_merge function. In this case, the function will create keys starting from 0 and increment them by 1 and assign them values from the given array.

PHP array_map() function
PHP array_merge_recursive() function

Add comment

Tutor Network

Share this

Learn PHP from A to Z