
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:
Output:
Explanation:
-
The array
$numbers
is spread into three separate arguments (2, 4, 6
), which are passed to thesum()
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:
Output:
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:
Output:
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:
Output:
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!
Leave a Comment