Skip to content

PHP Tutorial Arrays

The Spread Operator

Lesson 129 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

The spread operator ... unpacks an array into separate items. You can use it in function calls and inside array literals.

Merge arrays

index.php
PHP
<?php
$frontend = ["html", "css"];
$backend = ["php", "sql"];

$skills = [...$frontend, ...$backend, "git"];

echo implode(", ", $skills);
Output
OUTPUT
html, css, php, sql, git

Spread into function arguments

index.php
PHP
<?php
function area(int $width, int $height): int
{
    return $width * $height;
}

$size = [4, 5];

echo area(...$size);
Output
OUTPUT
20

String keys (PHP 8.1+)

Since PHP 8.1, you can spread arrays that have string keys. Later keys replace earlier ones.

index.php
PHP
<?php
$defaults = ["theme" => "light", "lang" => "en"];
$custom = ["theme" => "dark"];

$settings = [...$defaults, ...$custom];

print_r($settings);
Output
OUTPUT
Array
(
    [theme] => dark
    [lang] => en
)

This is how you apply “defaults, then overrides”. The right-hand array wins.

Spread vs + vs array_merge()

ExpressionResult for key "theme"Numeric keys
$a + $bThe left value winsLeft items kept, right ones with the same index ignored
array_merge($a, $b)The right value winsRe-numbered
[...$a, ...$b]The right value winsRe-numbered
index.php
PHP
<?php
$a = ["x" => 1, 5 => "five"];
$b = ["x" => 2, 5 => "cinco"];

print_r($a + $b);
print_r([...$a, ...$b]);
Output
OUTPUT
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.

index.php
PHP
<?php
$cart = ["pen", "book"];

$newCart = [...$cart, "bag"];

echo count($cart) . " vs " . count($newCart);
Output
OUTPUT
2 vs 3

Spread works on anything traversable

You can spread a generator or another Traversable too, not only arrays.

index.php
PHP
<?php
function numbers(): Generator
{
    yield 1;
    yield 2;
}

print_r([...numbers(), 3]);
Output
OUTPUT
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
info
Variadics use the same dots
In a function definition, ...$args collects arguments. In a call or array, ...$array spreads them out. Same symbol, opposite directions. See Variadic Functions.