Analysis and Comparison of Three Methods of Merging Arrays in PHP

There are three commonly used methods of merging arrays: array_merge(), array_merge_recursive(), +, one by one below

array_merge()

This function merges one or more arrays. When the input array has the same string key name , the latter one will overwrite the former . Values ​​for numeric indices in the parameter array are reordered , regardless of whether the numeric indices are the same or different.

code show as below:

$arr1 = array('name' => 'tom', 123, 456);
$arr2 = array('age' => 13, 'name' => 'peter', 'hello', 'world');
$arr = array_merge($arr1, $arr2);
var_dump($arr1);
var_dump($arr2);
var_dump($arr);

operation result:


array (size=3)
  'name' => string 'tom' (length=3)
  0 => int 123
  1 => int 456

array (size=4)
  'age' => int 13
  'name' => string 'peter' (length=5)
  0 => string 'hello' (length=5)
  1 => string 'world' (length=5)

array (size=6)
  'name' => string 'peter' (length=5)
  0 => int 123
  1 => int 456
  'age' => int 13
  2 => string 'hello' (length=5)
  3 => string 'world' (length=5)

array_merge_recursive()

This function recursively merges one or more arrays into an array when the input arrays have the same string key name , instead of overwriting .

code show as below:

$arr1 = array('name' => 'tom', 123, 456);
$arr2 = array('age' => 13, 'name' => 'peter', 'hello', 'world');
$arr = array_merge_recursive($arr1, $arr2);
var_dump($arr1);
var_dump($arr2);
var_dump($arr);

operation result:


array (size=3)
  'name' => string 'tom' (length=3)
  0 => int 123
  1 => int 456

array (size=4)
  'age' => int 13
  'name' => string 'peter' (length=5)
  0 => string 'hello' (length=5)
  1 => string 'world' (length=5)

array (size=6)
  'name' =>
    array (size=2)
      0 => string 'tom' (length=3)
      1 => string 'peter' (length=5)
  0 => int 123
  1 => int 456
  'age' => int 13
  2 => string 'hello' (length=5)
  3 => string 'world' (length=5)

+

When the plus sign merges the arrays, if the array has the same string key name or the same numerical index , the previous value will overwrite the latter value.

code show as below:

 

$arr1 = array('name' => 'tom', 123, 456);
$arr2 = array('age' => 13, 'name' => 'peter', 'hello', 'world');
$arr = $arr1 + $arr2;
var_dump($arr1);
var_dump($arr2);
var_dump($arr);

 

operation result:


array (size=3)
  'name' => string 'tom' (length=3)
  0 => int 123
  1 => int 456

array (size=4)
  'age' => int 13
  'name' => string 'peter' (length=5)
  0 => string 'hello' (length=5)
  1 => string 'world' (length=5)

array (size=4)
  'name' => string 'tom' (length=3)
  0 => int 123
  1 => int 456
  'age' => int 13

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325269486&siteId=291194637