Home > Article > Backend Development > Merge multiple arrays using PHP array_merge() function
PHP array_merge() function is a built-in function for merging multiple arrays. This function can combine multiple arrays into a new array. In this article, we will discuss how to merge multiple arrays using PHP array_merge() function.
How to use the PHP array_merge() function
The PHP array_merge() function has many uses, but the most common use is to merge two or more groups into one. The following is a simple example:
$array1 = array('a', 'b', 'c'); $array2 = array('d', 'e', 'f'); $result = array_merge($array1, $array2); print_r($result);
Output the following results:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
In the above example, we merged the two arrays $array1 and $array2 into a new array $result. This new array contains all elements of the two original arrays.
Details of using the PHP array_merge() function
When using the PHP array_merge() function, there are several details to pay attention to:
$array1 = array('a' => 1, 'b' => 2); $array2 = array('b' => 3, 'c' => 4); $result = array_merge($array1, $array2); print_r($result);
The output is as follows:
Array ( [a] => 1 [b] => 3 [c] => 4 )
In the above example, the $b key name in the array $array2 overwrites the $b key name in the array $array1, so The final result is 3 instead of 2. The $a key name in array $array1 and the $c key name in array $array2 are retained.
$array1 = array('a' => 1, 'b' => 2); $array2 = array('c' => 3, 'd' => 4); $result = array_merge($array1, $array2); print_r($result);
Output the following results:
Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 )
In the above example, the arrays $array1 and $array2 are both associative arrays. When they are merged, the PHP array_merge() function creates a new array and assigns them new key names using numerical indexes. The original key name is ignored.
$array1 = array('a' => array('b' => 1, 'c' => 2)); $array2 = array('a' => array('d' => 3, 'e' => 4)); $result = array_merge($array1, $array2); print_r($result);
Output the following results:
Array ( [a] => Array ( [b] => 1 [c] => 2 [d] => 3 [e] => 4 ) )
In the above example, the arrays $array1 and $array2 both contain a subarray named $a. When they are merged, the PHP array_merge() function will merge them recursively and create a new subarray. In the final result, the new subarray contains the original $b, $c, $d, and $e key values.
Summary
PHP array_merge() function is a very useful array function that can merge multiple arrays into one. We can use it to merge numeric or associative arrays, and we can also use it to merge multiple subarrays recursively. However, when using this function, we need to pay attention to some details to avoid unexpected results.
The above is the detailed content of Merge multiple arrays using PHP array_merge() function. For more information, please follow other related articles on the PHP Chinese website!