PHP append one array to another (not array_push or +) PHP append one array to another (not array_push or +) arrays arrays

PHP append one array to another (not array_push or +)


array_merge is the elegant way:

$a = array('a', 'b');$b = array('c', 'd');$merge = array_merge($a, $b); // $merge is now equals to array('a','b','c','d');

Doing something like:

$merge = $a + $b;// $merge now equals array('a','b')

Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b, it won't do anything.


Another way to do this in PHP 5.6+ would be to use the ... token

$a = array('a', 'b');$b = array('c', 'd');array_push($a, ...$b);// $a is now equals to array('a','b','c','d');

This will also work with any Traversable

$a = array('a', 'b');$b = new ArrayIterator(array('c', 'd'));array_push($a, ...$b);// $a is now equals to array('a','b','c','d');

A warning though:

  • in PHP versions before 7.3 this will cause a fatal error if $b is an empty array or not traversable e.g. not an array
  • in PHP 7.3 a warning will be raised if $b is not traversable


Why not use

$appended = array_merge($a,$b); 

Why don't you want to use this, the correct, built-in method.