We all know that two arrays in PHP can use + or array_merge, but there is still a difference between, and these differences if you understand the project will be fatal! This article summed up the introduction of PHP 2 methods of merging arrays, the need for friends can reference, the following to learn together.
Objective
In the previous merge array I always use array_merge()
this function, but recently I was in the change of work encountered a merge array of face questions, I was thinking is to convert two arrays into a string, and then converted to an array of output, the interviewer said this idea is not very right, Finished bulabula about the array basis of things, and then really because of experience, or the code is too little to write, unexpectedly have any method, today I Baidu a bit, originally there is ' + ' number,
array_merge_recursive()
, which can also be used to merge arrays, according to my memory, I wrote the word out to look at:
$a = array (' Color ' = ' red ', 5,6); $b = Array (' Color ' = ' blue ', ' type ' = ' fruit ', 6,7); $arr = Array_merge ($a, $b); Var_dump ($arr);
Array (size=6) ' color ' = = String ' Blue ' (length=4) 0 = int 5 1 = int 6 ' type ' = = String ' fruit ' (length=5) 2 = = Int 6 3 = = Int 7
The requirement is to get the same effect in the case of not being used array_merge()
;
( array_merge()
merging arrays combines the same key values of the associative array in the previous array, and the order of the key values in the indexed form.)
1. First use the array_merge_recursive () function to merge:
$a = array (' Color ' = ' red ', 5,6); $b = Array (' Color ' = ' blue ', ' type ' = ' fruit ', 6,7); $arr = Array_merge_recursive ($a, $b); Var_dump ($arr);
Output Result:
Array (size=6) ' color ' = = Array (size=2) 0 = = String ' Red ' (length=3) 1 = String ' Blue ' (length=4) 0 = = Int 5 1 = int 6 ' type ' = = String ' fruit ' (length=5) 2 = int 6 3 = int 7
It can be seen from the result array_merge_recursive()
that the function returns the value of the same key value as a new associative array with the key value as the key value of the two-dimensional array, and the other index forms are unaffected.
The next array_merge()
array key is not the same as the previous one, overwriting the previous value.
2. Take a look at the ' + ' case of the combined array:
$a = array (' Color ' = ' red ', 5,6); $b = Array (' Color ' = ' blue ', ' type ' = ' fruit ', 6,7); $arr = $a + $b; Var_dump ($arr);
Output Result:
Array (size=4) ' color ' = = String ' Red ' (length=3) 0 = int 5 1 = int 6 ' type ' = = String ' fruit ' (length=5)
As can be seen from this result, using the ' + ' sign to merge the array, is the front overlay behind, and the array_merge()
opposite, and it is array_merge()
more ruthless, if the contents of the array in the form of an index, after merging if the same key value will be overwritten!
The above is the whole content of this article, I hope that everyone's study has helped.