Both the "+" operator and array_merge():array array_merge (array array1, array array2 [, array ...]) can merge multiple arrays, but there is a slight difference in the use process.
array_merge is described in the reference manual as follows:
array_merge() merges the cells of two or more arrays, with the values in one array appended to the previous array. Returns the resulting array.
If the input array has the same string key name, the value after the key name will overwrite the previous value. However, if the array contains numeric keys, the subsequent values will not overwrite the original values but will be appended to them.
The difference between the two is:
1. When the array key name is a numeric key name, and there are numeric KEYs with the same name in the two arrays to be merged, using array_merge() will not overwrite the original value, while using "+" to merge the arrays will replace the first one. The value is returned as the final result, and those values in the subsequent arrays with the same key name are "discarded" (note: it is not overwriting but retaining the value that appears first). Example:
$array1 = array(1=>'0');
$array2 = array(1=> "data");
$result1 = $array2 + $array1;/*The result is the value of $array2*/
print_r($result);
$result = $array1 + $array2 ;/*The result is the value of $array1*/
print_r($result);
$result3 = array_merge($array2,$array1);/*The result is the value of $array2 and $array1, and the key name is reassigned*/
print_r($result3);
$result4 = array_merge($array1,$array2);/*The result is the value of $array1 and $array2, and the key name is reassigned*/
print_r($result4);
The output result is:
Array ( [1] => data )
Array ( [1] => 0 )
Array (
[0] => data
[1] => 0
)
Array
(
[0] => 0
[1] => data
)
2. When the same array key name is a character, the "+" operator is the same as when the key name is a number, but array_merge() will overwrite the previous value of the same key name.
example:
$array1 = array('asd'=>'0');
$array2 = array('asd' => "data");
$result1 = $array2 + $array1;/*The result is the value of $array2*/
print_r($result);
$result = $array1 + $array2 ;/*The result is the value of $array1*/
print_r($result);
$result3 = array_merge($array2,$array1);/*The result is $array1*/
print_r($result3);
$result4 = array_merge($array1,$array2);/*The result is $array2*/
print_r($result4);
The output result is:
Array ([asd] => data)
Array ( [asd] => 0 )
Array ( [asd] => 0 )
Array ( [asd] => data )