PHP combines two arrays in two ways: + and Array_merge differences

Source: Internet
Author: User
PHP combines two arrays in two ways: + and Array_merge differences

The combination of two arrays in PHP can use + or array_merge, but these two are still different, it is clear to understand the difference between the two approaches to the rapid development of the project is still very necessary.


The main difference is that when the same key name appears in two or more arrays, you need to be aware of the following two points: first of all, it is necessary to explain that the array key names in PHP can be divided into strings (associative arrays) or numbers (numeric arrays), where the multidimensional arrays are not discussed.

(1) When the key name is a number (numeric array), Array_merge () does not overwrite the original value, but the + merge array will return the first occurrence as the final result, and the values of the following array with the same key name "Discard" (not overwrite).

(2) When the key name is a character (associative array), + still returns the first occurrence as the final result, and "discards" the values of the following array with the same key name, but Array_merge () overwrites the previous value of the same key name.

This is illustrated by a few specific examples:

M:array (

[0] = a
[1] = b
)
N:array (
[0] = C
[1] = d
)
The m+n result is: Array (
[0] = a
[1] = b
)
The Array_merge (m,n) result is: Array (
[0] = a
[1] = b
[2] = C
[3] = d
)
M:array (
[1] = a
[2] = b
)
N:array (
[2] = C
[3] = d
)
The m+n result is: Array (
[1] = a
[2] = b
[3] = d
)
The Array_merge (m,n) result is: Array (
[0] = a
[1] = b
[2] = C
[3] = d
)
M:array (
[A] = a
[B] = b
)
N:array (
[b] + = C
[d] + D
)
The m+n result is: Array (
[A] = a
[B] = b
[d] + D
)
The Array_merge (m,n) result is: Array (
[A] = a
[b] + = C
[d] + D
)
  • 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.