PHP by Array_merge () and Array+array merge array difference and efficiency comparison

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.