In PHP development, we often encounter situations where we need to merge two or more arrays. In this case, we need to use the array merge function array_merge() provided by PHP.
The usage of the array_merge() function is very simple. It can accept any number of arrays as parameters, merge them into a new array and return it. Let's take a look at the specific usage:
$array1 = array('a', 'b', 'c'); $array2 = array('d', 'e', 'f'); $result = array_merge($array1, $array2); print_r($result); //输出:Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
In the above example, we declared two arrays $array1 and $array2, and then used array_merge( ) function merges them into a new array $result.
$array1 = array('a', 'b', 'c'); $array2 = array('d', 'e', 'f'); $array3 = array('g', 'h', 'i'); $result = array_merge($array1, $array2, $array3); print_r($result); //输出:Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f [6] => g [7] => h [8] => i )
In the above example, we declared three arrays $array1, $array2 and $array3, and then used the array_merge() function to merge them into A new array $result.
$array1 = array('a' => 1, 'b' => 2, 'c' => 3); $array2 = array('a' => 4, 'd' => 5, 'e' => 6); $result = array_merge($array1, $array2); print_r($result); //输出:Array ( [a] => 4 [b] => 2 [c] => 3 [d] => 5 [e] => 6 )
In the above example, we declared two arrays $array1 and $array2 with different key values. When using array_merge( ) function will overwrite the element with key "a" in $array1 array when merging them, because the element value with key "a" in $array2 array is greater than the element value with key "a" in $array1 array.
$array1 = array('a' => array('a1', 'a2'), 'b' => array('b1', 'b2')); $array2 = array('a' => array('a3', 'a4'), 'c' => array('c1', 'c2')); $result = array_merge($array1, $array2); print_r($result); //输出:Array ( [a] => Array ( [0] => a3 [1] => a4 ) [b] => Array ( [0] => b1 [1] => b2 ) [c] => Array ( [0] => c1 [1] => c2 ) )
The above example is to merge a two-dimensional array $array1
and $array2
, using the array_merge() function When you merge them, each one-dimensional array in the two-dimensional array is merged as a whole.
To sum up, the array_merge() function is a commonly used array merging function in PHP, which can help us complete array operations more quickly during development.
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!