Home >Backend Development >PHP Tutorial >How to merge two PHP arrays into one array
How to merge two PHP arrays into one array
In PHP development, we often need to merge two arrays into one array. This operation is very common in data processing and array operations. This article will show you how to merge two arrays simply and efficiently using PHP.
PHP provides two functions to merge arrays, namely array_merge()
and array_merge_recursive()
. Below we introduce the usage and sample code of these two functions respectively.
array_merge()
is a common function in PHP for manipulating arrays. It combines two arrays into one array and returns the combined result. If the incoming arrays have the same string key name, the subsequent array will overwrite the previous array.
The following is a sample code that uses the array_merge()
function to merge arrays:
$array1 = array("apple", "banana"); $array2 = array("orange", "grape"); $result = array_merge($array1, $array2); print_r($result);
Run the above code, you will get the following output:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
array_merge_recursive()
Function is similar to array_merge()
function, it merges two or more arrays into one Multidimensional arrays and return the combined result. If the incoming arrays have the same string key, it will create an array within the array, retaining the values of the same key.
The following is a sample code that uses the array_merge_recursive()
function to merge arrays:
$array1 = array("name" => "John", "age" => 30); $array2 = array("name" => "David", "hobby" => "reading"); $result = array_merge_recursive($array1, $array2); print_r($result);
Run the above code, you will get the following output:
Array ( [name] => Array ( [0] => John [1] => David ) [age] => 30 [hobby] => reading )
The above example code shows how to merge two arrays using the array_merge()
and array_merge_recursive()
functions. Depending on the actual situation, you can choose a function that suits your needs to merge arrays.
It should be noted that when the array_merge()
function merges associative arrays, the later array will overwrite the previous array; while the array_merge_recursive()
function will repeat Create an array at the key name to save the value of the same key name.
Hope the above content will help you understand how to merge two arrays in PHP. Array merging operations can be easily implemented using appropriate functions. If you have any questions or other PHP-related issues, you can continue to study PHP-related documents and tutorials.
The above is the detailed content of How to merge two PHP arrays into one array. For more information, please follow other related articles on the PHP Chinese website!