In PHP, there are many ways to merge arrays. Two of the commonly used methods will be introduced below.
Method 1: Use the array_merge function
The array_merge function is used to merge one or more arrays and return a merged array. The sample code is as follows:
$arr1 = array('apple', 'banana'); $arr2 = array('orange', 'pear'); $arr3 = array('grape', 'kiwi'); $result = array_merge($arr1, $arr2, $arr3); print_r($result);
The output result is as follows:
Array ( [0] => apple [1] => banana [2] => orange [3] => pear [4] => grape [5] => kiwi )
Explanation: The array_merge function can merge any number of arrays. After merging, the key names of the arrays will be redistributed. For the same key names, the following The value will overwrite the previous value.
Method 2: Use the " " operator
The " " operator is used to merge two arrays and return a merged array. The sample code is as follows:
$arr1 = array('apple', 'banana'); $arr2 = array('orange', 'pear'); $result = $arr1 + $arr2; print_r($result);
The output result is as follows:
Array ( [0] => apple [1] => banana [2] => orange [3] => pear )
Explanation: The " " operator can only merge two arrays. The key name of the merged array shall be based on the left array. If the key If the names are the same, the value of the array on the right is ignored.
It should be noted that different merging methods may lead to different results, and the appropriate method should be selected according to needs.
The above is the detailed content of In php, the method used to merge arrays is. For more information, please follow other related articles on the PHP Chinese website!