It is well known that merging two arrays can use Array_merge (), which is a function provided by PHP. It is also possible to merge arrays by array, which is directly different from each other, which one is more efficient?
Array_merge () Format: array array_merge (array...] )Note (difference):
- If the merged array uses the associated index and the same key name is in the array, the value following the key name overrides the previous value.
- If the merged array uses a numeric index with the same key name in the array, the subsequent value will not overwrite the original value, but append to the back.
- If only one array is given and the array is a numeric index, the key name is re-indexed in a sequential manner.
$array + $array Note (difference):
- If the merged array has the same key name, the first occurrence of the value is returned as the final result (as opposed to the Array_merge associated index)
Cycle time of 100,000 times
$arr1 = [0,1,2,3];$arr2 = [‘0‘=>0,1,2,‘5‘=>3];var_dump(array_merge($arr1,$arr2));echo ‘<br/>‘;var_dump($arr1+$arr2);echo ‘测试array_merge()和+的效率‘;echo ‘<br/>‘;$execTime = 100000;$time = time();for ($i = 0; $i < $execTime; $i++) { array_merge($arr1,$arr2);}echo ‘用时:‘ .(time() - $time);echo ‘<br/>‘;$time = time();for ($i = 0; $i < $execTime; $i++) { $arr1+$arr2;}echo ‘用时:‘ .(time() - $time);echo ‘<br/>‘;
Output Result:
Array_merge (): 6s
$array + $array: 0s
Summarize
Both Array_merge () and + can act as merged arrays, but they handle the same key differently, Array_merge () returns the value of the following key, and + returns the value of the first key. + efficiency is higher than array_merge ();
PHP by Array_merge () and Array+array merge array difference and efficiency comparison