The spread operator ... unpacks an array into separate items. You can use it in function calls and inside array literals.
Merge arrays
<?php
$frontend = ["html", "css"];
$backend = ["php", "sql"];
$skills = [...$frontend, ...$backend, "git"];
echo implode(", ", $skills);
html, css, php, sql, git
Spread into function arguments
<?php
function area(int $width, int $height): int
{
return $width * $height;
}
$size = [4, 5];
echo area(...$size);
20
String keys (PHP 8.1+)
Since PHP 8.1, you can spread arrays that have string keys. Later keys replace earlier ones.
<?php
$defaults = ["theme" => "light", "lang" => "en"];
$custom = ["theme" => "dark"];
$settings = [...$defaults, ...$custom];
print_r($settings);
Array
(
[theme] => dark
[lang] => en
)
This is how you apply “defaults, then overrides”. The right-hand array wins.
Spread vs + vs array_merge()
| Expression | Result for key "theme" | Numeric keys |
|---|---|---|
$a + $b | The left value wins | Left items kept, right ones with the same index ignored |
array_merge($a, $b) | The right value wins | Re-numbered |
[...$a, ...$b] | The right value wins | Re-numbered |
<?php
$a = ["x" => 1, 5 => "five"];
$b = ["x" => 2, 5 => "cinco"];
print_r($a + $b);
print_r([...$a, ...$b]);
Array
(
[x] => 1
[5] => five
)
Array
(
[x] => 2
[0] => five
[1] => cinco
)
Copy and add
The spread operator is a tidy way to make a modified copy without changing the original.
<?php
$cart = ["pen", "book"];
$newCart = [...$cart, "bag"];
echo count($cart) . " vs " . count($newCart);
2 vs 3
Spread works on anything traversable
You can spread a generator or another Traversable too, not only arrays.
<?php
function numbers(): Generator
{
yield 1;
yield 2;
}
print_r([...numbers(), 3]);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Variadics use the same dots
...$args collects arguments. In a call or array, ...$array spreads them out. Same symbol, opposite directions. See Variadic Functions.