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.
It's a pretty old post, but I want to add something about appending one array to another:
If
- one or both arrays have associative keys
- the keys of both arrays don't matter
you can use array functions like this:
array_merge(array_values($array), array_values($appendArray));
array_merge doesn't merge numeric keys so it appends all values of $appendArray. While using native php functions instead of a foreach-loop, it should be faster on arrays with a lot of elements.
Addition 2019-12-13: Since PHP 7.4, there is the possibility to append or prepend arrays the Array Spread Operator way:
$a = [3, 4];
$b = [1, 2, ...$a];
As before, keys can be an issue with this new feature:
$a = ['a' => 3, 'b' => 4];
$b = ['c' => 1, 'a' => 2, ...$a];
"Fatal error: Uncaught Error: Cannot unpack array with string keys"
$a = [3 => 3, 4 => 4];
$b = [1 => 1, 4 => 2, ...$a];
array(4) { [1]=> int(1) [4]=> int(2) [5]=> int(3) [6]=> int(4) }
$a = [1 => 1, 2 => 2];
$b = [...$a, 3 => 3, 1 => 4];
array(3) { [0]=> int(1) [1]=> int(4) [3]=> int(3) }
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.