PHP 7.4 : Array Spread Operator
20, December 2019

PHP already has spread operator (...) for argument unpacking. From now on, we can unpack/spread arrays too.


How to unpack Arrays?

Say, we have an array of odd numbers, we want to merge them with another array of even numbers. We can use spread operator to do this

<?php

$odd_numbers = [1, 3, 5, 6, 7, 9];

$even_numbers = [2, 4, 6, 8];

$all_numbers = [0, ...$odd_numbers, ... $even_numbers];

print_r($all_numbers);
// Array ( [0] => 0 [1] => 1 [2] => 3 [3] => 5 [4] => 6 [5] => 7 [6] => 9 [7] => 2 [8] => 4 [9] => 6 [10] => 8 )

Previously, we needed to use array_merge() to merge arrays, but now we can achieve same thing without calling any functions. Not only arrays, Spread Operator works on any objects implementing Traversable too.


Note: Currently arrays with numeric keys are supported only. We can't merge arrays with string keys using spread operator.