Home > Article > Backend Development > How to merge two arrays in php
How to merge two arrays in php?
In PHP, you can use the array_merge() function to merge two arrays.
Definition and usage
The array_merge() function merges one or more arrays into one array.
Tip: You can input one or more arrays to 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 input only an array to the array_merge() function, and the keys are integers, the function will return a new array with integer keys, with keys re-indexed starting at 0 ( See Example 1) below.
Tip: The difference between this function and the array_merge_recursive() function is that it handles the case where two or more array elements have the same key name. array_merge_recursive() does not perform key name overwriting, but recursively combines multiple values with the same key name into an array.
Syntax
array_merge(array1,array2,array3...)
Parameters
array1 Required. Specifies an array.
array2 Optional. Specifies an array.
array3 Optional. Specifies an array.
Return value: Return the merged array.
Recommended: "PHP Tutorial"
Example 1
Combine two arrays into one array:
<?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2)); ?>
Output:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Example 2
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)); ?>
Output:
Array ( [a] => red [b] => yellow [c] => blue )
Example 3
Use only one array parameter with integer key name:
<?php $a=array(3=>"red",4=>"green"); print_r(array_merge($a)); ?>
Output:
Array ( [0] => red [1] => green )
The above is the detailed content of How to merge two arrays in php. For more information, please follow other related articles on the PHP Chinese website!