Home >Backend Development >PHP Tutorial >PHP merge array + the difference between array_merge_PHP tutorial
In PHP, you can use + or array_merge to merge two arrays, but there are still differences between the two. A clear understanding of the difference between the two processing methods is still very necessary for the rapid development of the project.
The main difference is that when the same key name appears in two or more arrays, you need to pay attention to the following two points:
First of all, it is necessary to explain that array key names in PHP can be roughly divided into strings (associative arrays) or numbers (numeric arrays). Multi-dimensional arrays will not be discussed here.
(1) When the key name is a number (numeric array), array_merge() will not overwrite the original value, but + merge array will return the first value as the final result, and the subsequent arrays with the same key name will be returned Those values are "discarded" (not overwritten).
(2) When the key name is a character (associative array), + still returns the first appearing value as the final result, and "discards" those values in subsequent arrays with the same key name, but array_merge() will overwrite it at this time Remove the previous value with the same key name.
The following is explained through several specific examples:
m:Array (
[0] => a
[1] => b
)
n:Array (
[0] => c
[1] => d
)
The result of m+n is: Array (
[0] => a
[1] => b
)
The result of array_merge(m,n) is: Array (
[0] => a
[1] => b
[2] => c
[3] => d
)
m:Array (
[1] => a
[2] => b
)
n:Array (
[2] => c
[3] => d
)
The result of m+n is: Array (
[1] => a
[2] => b
[3] => d
)
The result of array_merge(m,n) is: Array (
[0] => a
[1] => b
[2] => c
[3] => d
)
m:Array (
[a] => a
[b] => b
)
n:Array (
[b] => c
[d] => d
)
The result of m+n is: Array (
[a] => a
[b] => b
[d] => d
)
The result of array_merge(m,n) is: Array (
[a] => a
[b] => c
[d] => d
)