PHP Spread Operator: A Complete Guide for Cleaner Code
The spread operator in PHP is a powerful yet often overlooked feature that can make your code cleaner, more concise, and easier to maintain. Introduced in PHP 7.4 for arrays and available earlier for function arguments, it allows you to unpack arrays and pass their elements directly into functions or merge them effortlessly.
Whether you’re simplifying function calls or combining multiple arrays, the spread operator can save you time and reduce boilerplate code.
What is the Spread Operator in PHP?
In PHP, the spread operator is represented by three dots (...). It is used in two main ways:
- Function Arguments – Unpacking an array into separate parameters.
- Array Destructuring / Merging – Spreading array elements into another array.
1. Spread Operator with Function Arguments
Before PHP introduced the spread operator, passing multiple values from an array to a function meant using functions like call_user_func_array().
Example without spread operator:
function greet($first, $second, $third) {
echo "$first, $second, and $third!";
}
$names = ['Alice', 'Bob', 'Charlie'];
// Old way
call_user_func_array('greet', $names);
With the spread operator:
greet(...$names);
// Output: Alice, Bob, and Charlie!
This is cleaner, faster, and more readable.
2. Spread Operator with Arrays (PHP 7.4+)
Starting from PHP 7.4, you can use the spread operator to merge arrays without calling array_merge().
Example – Merging Arrays:
$array1 = [1, 2, 3];
$array2 = [4, 5];
$array3 = [...$array1, ...$array2, 6, 7];
print_r($array3);
// Output: [1, 2, 3, 4, 5, 6, 7]
You can even mix array values and spreads:
$numbers = [0, ...$array1, 8];
print_r($numbers);
// Output: [0, 1, 2, 3, 8]
3. Combining Spread Operator with Associative Arrays
For associative arrays, keys must be unique, and later values overwrite earlier ones:
$a = ['name' => 'Alice', 'role' => 'Developer'];
$b = ['role' => 'Manager', 'age' => 30];
$merged = [...$a, ...$b];
print_r($merged);
// Output: ['name' => 'Alice', 'role' => 'Manager', 'age' => 30]
4. Practical Use Cases of Spread Operator
✅ Simplifying function calls
✅ Merging multiple arrays without array_merge()
✅ Cloning and extending arrays quickly
✅ Unpacking parameters in dynamic function calls
5. Things to Keep in Mind
-
PHP Version – Array unpacking with
...works only in PHP 7.4+. -
Associative Arrays – Keys are preserved, but duplicates will be overwritten by later arrays.
-
Performance – Spread operator is faster and cleaner for small to medium arrays, but for huge datasets, benchmark against
array_merge(). -
- *
Conclusion
The PHP spread operator is a simple yet powerful feature that can save you from repetitive array merging and complex function calls. If you’re working with PHP 7.4 or newer, it’s a must-have tool in your coding arsenal.
Start using ... in your next project to write cleaner, more efficient PHP code.