PHP: Merging Arrays with array_merge() and Spread Syntax

Last updated on July 13, 2021 A Goodman Loading... Post a comment

In order to merge arrays in PHP (version 7 or 8), you can use the spread syntax (AKA argument unpacking, splat operator) or the array_merge() method. A few examples below will help you understand clearly.

Notes:

  • If the input arrays have the same string keys, the later value for that key will overwrite the previous one.
  • Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Example 1: Using the spread syntax

<?php
  $animals = ['dog', 'cat', 'snake', 'pig', 'chicken'];
  $fruits = ['apple', 'banana', 'water melon'];
  $things = [...$animals, ...$fruits];

  echo '<pre>';
  print_r($things);
  echo '</pre>';
  ?>

Output:

Array
(
    [0] => dog
    [1] => cat
    [2] => snake
    [3] => pig
    [4] => chicken
    [5] => apple
    [6] => banana
    [7] => water melon
)

Example 2: Using the array_merge method

Code:

<?php
  $arr1 = [1, 2, 3];
  $arr2 = [4, 5, 6];
  $arr3 = array_merge($arr1, $arr2);

  echo '<pre>';
  print_r($arr3);
  echo '</pre>';
  ?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

Example 3: Using the array_merge method + input arrays have the same string keys

<?php
  $arr1 = [
    'a' => 'Alligator',
    'b' => 'Bird',
    'c' => 'Cat'
  ];

  $arr2 = [
    'c' => 'Tiger',
    'd' => 'Dog',
    'e' => 'Elephant'
  ];

  $arr3 = array_merge($arr1, $arr2);

  echo '<pre>';
  print_r($arr3);
  echo '</pre>';
  ?>

Output:

Array
(
    [a] => Alligator
    [b] => Bird
    [c] => Tiger
    [d] => Dog
    [e] => Elephant
)

Example 3: Using the array_merge method with more complex arrays

<?php
  $men = [
    [
      'name' => 'Jack',
      'age' => 32
    ],
    [
      'name' => 'Steve',
      'age' => 39
    ]
  ];

  $women = [
    [
      'name' => 'Marry',
      'age' => 24
    ],
    [
      'name' => 'Sam',
      'age' => 31
    ]
  ];

  $people = array_merge($men, $women);

  echo '<pre>';
  print_r($people);
  echo '</pre>';
  ?>

Output:

Array
(
    [0] => Array
        (
            [name] => Jack
            [age] => 32
        )

    [1] => Array
        (
            [name] => Steve
            [age] => 39
        )

    [2] => Array
        (
            [name] => Marry
            [age] => 24
        )

    [3] => Array
        (
            [name] => Sam
            [age] => 31
        )

)

That’s it, my friends. Happy coding with PHP and have a nice day.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles