Notes for using php array_merge Functions

Source: Internet
Author: User

Notes for using php array_merge Functions

This article mainly introduces a problem that needs to be paid attention to when using the php array_merge function. This article describes the problem that array_merge does not merge the number key names when merging arrays. You need to pay attention when using this function. For more information, see

 

When using the array_merge function in php, the same key name will be overwritten, but please refer to the following code:

The Code is as follows:


$ A1 = array (1 => 'abc', 3 => 10 );
$ A2 = array (1 => 'efg', 3 => 20 );
Print_r (array_merge ($ a1, $ a2 ));

 

What will be output? We expected:

The Code is as follows:


Array
(
[1] => efg
[3] => 20
)

 

Actually, the output is:

 

The Code is as follows:


Array
(
[0] => abc
[1] => 10
[2] => efg
[3] => 20
)

 

Not only is it not overwritten, but the number key is re-indexed continuously.

At first thought this was a bug, and then turned over the php manual http://php.net/manual/zh/function.array-merge.php

「 If the input array contains the same string key name, the value after the key name overwrites the previous one. However, if the array contains a number key name, the subsequent values will not overwrite the original values, but will be appended to the back.
If only one array is assigned and the array is indexed by number, the key name is re-indexed continuously .」

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.