PHP - Spread Operator (...)

The spread operator (...) in PHP is used to unpack arrays and pass multiple arguments to functions. It simplifies array handling and function calls by spreading elements from an array into individual arguments.

The spread operator was introduced in PHP 5.6 for function arguments and later expanded in PHP 7.4 to allow array unpacking.


1. Using the Spread Operator in Function Arguments

The spread operator allows passing an array’s elements as individual arguments to a function.

Example:

<?php function sum($a, $b, $c) { return $a + $b + $c; } $numbers = [2, 4, 6]; echo sum(...$numbers); // Equivalent to sum(2, 4, 6) ?>

Output:

12

Explanation:

  • The array $numbers is spread into three separate arguments (2, 4, 6), which are passed to the sum() function.

  • Without the spread operator, you would need to manually extract values from the array.


2. Using the Spread Operator in Variadic Functions

A variadic function can accept an arbitrary number of arguments using ... in the parameter list.

Example:

<?php function multiply(...$nums) { return array_product($nums); } echo multiply(2, 3, 4); // 2 * 3 * 4 = 24 ?>

Output:

24

Explanation:

  • The multiply() function accepts multiple arguments, which are packed into an array using ...$nums.

  • array_product() multiplies all the numbers.


3. Using the Spread Operator to Merge Arrays (PHP 7.4+)

Starting from PHP 7.4, the spread operator can be used to merge arrays.

Example:

<?php $arr1 = [1, 2, 3]; $arr2 = [4, 5, 6]; $merged = [...$arr1, ...$arr2]; print_r($merged); ?>

Output:

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

Explanation:

  • Both $arr1 and $arr2 are spread into a new array, merging them into one.

  • This is more readable than using array_merge($arr1, $arr2).


4. Combining Arrays with Additional Values

You can also mix arrays with individual values.

Example:

<?php $fruits = ['apple', 'banana']; $moreFruits = ['grape', 'orange']; $allFruits = ['mango', ...$fruits, 'pineapple', ...$moreFruits]; print_r($allFruits); ?>

Output:

Array ( [0] => mango [1] => apple [2] => banana [3] => pineapple [4] => grape [5] => orange )

Explanation:

  • The spread operator allows inserting additional elements anywhere in the array.


Key Takeaways

✅ The spread operator (...) unpacks arrays into separate values.
✅ It can be used in function arguments, variadic functions, and array merging.
✅ From PHP 7.4+, it provides an easier way to merge arrays without using array_merge().


Conclusion

The spread operator in PHP makes working with arrays and functions more flexible and concise. Whether passing function arguments dynamically, merging arrays, or creating variadic functions, it simplifies code readability and efficiency.

Start using the spread operator today to write cleaner, more efficient PHP code