An analysis of the difference between PHP merge array + and array_merge

  • 2020-03-31 21:01:09
  • OfStack

The main difference is that if the same key name appears in two or more arrays, the key name is either a string or a number

1) when the key is named a number, array_merge() does not override the original value, but the + merge array returns the first value as the final result, and "abandons" (not overrides) those values with the same key name in subsequent arrays

2) when the key is named character, + still returns the first value as the final result, and "throws out" the values of the later array with the same key name, but array_merge() overrides the previous value with the same key name

Note that the array key form 'number' is equivalent to a number
 
$a = array('a','b'); 
$b = array('c', 'd'); 
$c = $a + $b; 
var_dump($a); 
var_dump(array_merge($a, $b)); 

$a = array(0 => 'a', 1 => 'b'); 
$b = array(0 => 'c', 1 => 'b'); 
$c = $a + $b; 
var_dump($c); 
var_dump(array_merge($a, $b)); 

$a = array('a', 'b'); 
$b = array('0' => 'c', 1 => 'b'); 
$c = $a + $b; 
var_dump($c); 
var_dump(array_merge($a, $b)); 

$a = array(0 => 'a', 1 => 'b'); 
$b = array('0' => 'c', '1' => 'b'); 
$c = $a + $b; 
var_dump($c); 
var_dump(array_merge($a, $b)); 

The results of
 
array 
0 => string 'a' (length=1) 
1 => string 'b' (length=1) 
2 => string 'c' (length=1) 
3 => string 'd' (length=1) 

array 
0 => string 'a' (length=1) 
1 => string 'b' (length=1) 

array 
0 => string 'a' (length=1) 
1 => string 'b' (length=1) 
2 => string 'c' (length=1) 
3 => string 'b' (length=1) 

array 
0 => string 'a' (length=1) 
1 => string 'b' (length=1) 

array 
0 => string 'a' (length=1) 
1 => string 'b' (length=1) 
2 => string 'c' (length=1) 
3 => string 'b' (length=1) 

array 
0 => string 'a' (length=1) 
1 => string 'b' (length=1) 

array 
0 => string 'a' (length=1) 
1 => string 'b' (length=1) 
2 => string 'c' (length=1) 
3 => string 'b' (length=1) 

Related articles: