a::merge($array1, $array2, $append = true)

Merges arrays recursively

  • $array1 (array)
  • $array2 (array)
  • $append (boolean)
    Behavior for elements with numeric keys; if true: elements are appended, keys are reset; if false: elements are overwritten, keys are preserved
  • return (array)

Example

Simple example

<?php
$array1 = [
  0 => 'cat',
  1 => 'dog',
  2 => 'bird',
];

$array2 = [
  'a' => 'elephant',
  'b' => 'kangaroo',
  'c' => 'hippopotamus',
];

$merged = a::merge($array1, $array2);
var_dump($merged);

Result:

array
  0   => 'cat'
  1   => 'dog'
  2   => 'bird'
  'a' => 'elephant'
  'b' => 'kangaroo'
  'c' => 'hippopotamus'

Appending values

If the $append param is set to true (default), elements with numeric keys are appended and not overwritten:

<?php
$array1 = [
  1 => 'cat',
  2 => 'dog',
  3 => 'bird',
];

$array2 = [
  1 => 'elephant',
  2 => 'kangaroo',
  3 => 'hippopotamus',
];

$merged = a::merge($array1, $array2);
var_dump($merged);

Result:

array
  0 => 'cat'
  1 => 'dog'
  2 => 'bird'
  3 => 'elephant'
  4 => 'kangaroo'
  5 => 'hippopotamus'

The resulting numeric keys are renumbered.

Overwriting values

<?php
$array1 = [
  1 => 'cat',
  2 => 'dog',
  3 => 'bird',
];

$array2 = [
  1 => 'elephant',
  2 => 'kangaroo',
  3 => 'hippopotamus',
];

$merged = a::merge($array1, $array2, false);
var_dump($merged);

Result:

array
  1 => 'elephant'
  2 => 'kangaroo'
  3 => 'hippopotamus'

Recursive merging

If both arrays have an element of type array for the same key, the merging will be done recursively:

<?php
$array1 = [
  'animals' => ['cat', 'dog', 'bird']
];

$array2 = [
  'animals' => ['elephant', 'kangaroo', 'hippopotamus']
];

$merged = a::merge($array1, $array2);
var_dump($merged);

Result:

array
  'animals' => array
    0 => 'cat'
    1 => 'dog'
    2 => 'bird'
    3 => 'elephant'
    4 => 'kangaroo'
    5 => 'hippopotamus'

Is something missing or incorrect? Edit this page on Github…