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.

$iterator = [1, ...new ArrayIterator([2, 3, 4])]; //[1, 2, 3, 4]


Note:

  • Currently arrays with numeric keys are supported only. We can't merge arrays with string keys using spread operator.
$stringlyKey = ['a' => 1, ...['b' => 2, 'c' => 3]];
// Fatal error: Cannot unpack array with string keys
  • It's not possible to unpack an array by reference.
$arr1 = [1, 2, 3];

$arr2 = [4, ...&$arr1]; // Parse error: syntax error


Update: Support for unpacking arrays with string keys has been added in PHP 8.1


Write comment about this article: