Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 147 ยท Arrays

Destructuring and Spread

Unpack PHP arrays with [$a, $b] = ..., keyed and nested destructuring, swaps and foreach, then merge arrays and arguments with the ... spread operator.

Arrays often arrive as packages: a function returns a pair of values, a database row holds several columns, a line of CSV splits into fields. Destructuring opens the package in one statement and puts each piece into its own variable. The opposite job, taking several arrays (or one array of arguments) and spreading their elements out into a new place, is done by the spread operator ....

Both features are short pieces of syntax, but they change how PHP code reads. Compare $name = $row[0]; $email = $row[1]; $age = $row[2]; with [$name, $email, $age] = $row;. This lesson covers every form: positional and keyed destructuring, skipping values, nested patterns, swapping, destructuring inside foreach, by-reference destructuring, and spreading arrays and arguments, including the string-key rules added in PHP 8.1.

You should already be comfortable with indexed arrays and associative arrays. Functions that return arrays come from Functions.

Positional destructuring

Put variables inside square brackets on the left side of =, and PHP assigns the array's elements to them in order: the element with key 0 to the first variable, key 1 to the second, and so on.

PHP Unpacking a list into variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The left side looks like an array literal, but it's a pattern: it describes where values go, not a new array. Extra elements on the right are ignored, and an empty slot ([, , $third]) skips one position.

The older list() syntax

Before PHP 7.1 the only way to write this was list():

PHP
list($red, $green, $blue) = $rgb;   // same as [$red, $green, $blue] = $rgb;

list() still works and you'll meet it in older code, but the short [...] form is the modern style and is what this tutorial uses.

Positional means "by integer key"

Positional destructuring doesn't care about the order elements were added. It looks up keys 0, 1, 2. If one of those keys is missing, you get a warning and the variable becomes null:

PHP When a key is missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows a=zero b=one, which proves the lookup is by key. The second part prints Warning: Undefined array key 2 in main.php on line 7 and then NULL. That warning is deliberate here: it's the same warning you'd get from $short[2]. Real code should check count() first or provide defaults, for example with [$p, $q, $r] = $short + [null, null, 'default'];, which uses the array union operator to fill in missing keys.

Keyed destructuring

Associative arrays have names, not positions. Write 'key' => $variable pairs inside the pattern to pull values out by key. The order of the pairs doesn't matter, and you only list the keys you want:

PHP Destructuring an associative array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This style is especially useful when a function returns several named results. Returning ['total' => ..., 'count' => ...] and destructuring by key is self-documenting, and the caller can't confuse the order.

You can't mix the two styles in one pattern. [$a, 'name' => $b] = $row; is a compile-time error: "Cannot mix keyed and unkeyed array entries in assignments". If you need a numeric key in a keyed pattern, write it explicitly: [0 => $a, 'name' => $b] = $row;.

Swapping and returning several values

Destructuring evaluates the right side completely before it assigns anything. That makes it the cleanest way to swap two variables, with no temporary variable:

PHP Swaps and multiple return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The @return array{int, int} comments are PHPDoc "array shapes". PHP ignores them, but editors and static analyzers use them to check that callers destructure correctly. You'll see more of this style in Type Declarations.

Nested destructuring

Patterns can contain patterns. If an element is itself an array, put another bracket pair in that position. Keyed and positional patterns can be nested inside each other, as long as each single bracket level sticks to one style:

PHP Nested patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Laying a big pattern over several lines, as above, mirrors the shape of the data and keeps it readable. If a pattern gets deeper than two levels, consider whether a small class (from Classes, Properties and Methods) would describe the data better.

Destructuring in foreach

The most common place to destructure is the head of a foreach loop. Instead of taking each row as $row and then reading $row['name'], unpack it directly. This was introduced briefly in foreach Loops; here it is with both styles:

PHP foreach with patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The loop variables are fresh copies on each pass, just like a plain foreach ($users as $user). Data from Multidimensional Arrays, such as rows fetched from a database, fits this pattern perfectly.

Destructuring by reference

Since PHP 7.3 you can put & before a variable in a pattern. That variable then becomes a reference to the array element, so writing to the variable changes the array:

PHP
$point = [10, 20];
[$x, &$y] = $point;
$y = 99;
print_r($point);   // [10, 99]: $y is bound to $point[1]

It also works in foreach ($rows as [&$a, $b]). Use it sparingly: references are easy to forget, and the dangling-reference bug applies here too. Returning a modified copy is usually clearer.

The spread operator in arrays

Three dots before an array inside an array literal mean "insert all of this array's elements here". It's the inverse of destructuring: instead of taking an array apart into variables, you pour arrays into a new one.

PHP Spreading arrays into a new array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The renumbering matters: spread treats integer keys as positions, so $sparse's keys 5 and 9 become 0 and 1. The last example spreads a generator, which works with any Traversable object.

String keys (PHP 8.1)

Before PHP 8.1, spreading an array with string keys was an error. Since 8.1 it's allowed, and it follows the same rules as array_merge(): string keys are kept, and when the same string key appears twice, the later value wins.

PHP Spreading arrays with string keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The === check prints bool(true): [...$a, ...$b] and array_merge($a, $b) produce identical arrays. The union operator + works the other way around (the left side's keys win, and integer keys aren't renumbered), so $choice + $defaults also merges options, but $defaults + $choice keeps every default. The table sums it up:

Expression Duplicate string key Integer keys
[...$a, ...$b] value from $b wins renumbered 0, 1, 2 โ€ฆ
array_merge($a, $b) value from $b wins renumbered 0, 1, 2 โ€ฆ
$a + $b value from $a wins kept; $b's duplicates dropped

See Array Functions for more on array_merge().

Spreading arguments into a function call

The same ... works in a function call: it turns an array into separate arguments. It pairs naturally with variadic parameters (...$numbers in a function definition), which collect separate arguments into an array. Both were introduced in Parameters and Arguments.

PHP Argument unpacking and named arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Some rules to remember for calls:

  • A spread can follow positional arguments (total(5, ...$cart)), but a positional argument can't follow a spread: total(...$cart, 5) is the compile error "Cannot use positional argument after argument unpacking".
  • With string keys, each key must match a parameter name (or be collected by a variadic). An unknown key like ['colour' => 'red'] throws an Error: "Unknown named parameter $colour".
  • In an array or argument list, integer keys must come before string keys. makeLabel(...['bold' => true, 'Draft']) fails with "Cannot use positional argument after named argument during unpacking".

Spread copies values. [...$a] builds a new array, and changing it never affects $a. You can't spread by reference ([...&$a] is a parse error); if a function needs to modify the caller's array, pass the array itself by reference instead.

Choosing the right tool

  • Pull a few values out of a small, fixed-shape array: destructuring.
  • Loop over rows and use their fields: destructuring in foreach.
  • Combine lists or override defaults: spread (or array_merge(), which is identical).
  • Keep existing keys when merging: the + operator.
  • Call a function with arguments stored in an array: argument unpacking f(...$args).

When a destructuring pattern starts listing five or six keys, or you destructure the same shape in many places, the array is really a record. That's the signal to move to objects, which is exactly where the next chapter begins.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? [, $b, , $d] = [10, 20, 30, 40]; echo $b + $d;

    The empty slots skip keys 0 and 2, so $b is 20 and $d is 40. Their sum is 60.
  2. 2. After $a = 1; $b = 2; [$a, $b] = [$b, $a];, what are $a and $b?

    The right side [2, 1] is built first, then assigned, so the values swap without a temporary variable.
  3. 3. Which pattern is a compile-time error?

    One bracket level can't mix keyed and unkeyed entries. Writing the integer key explicitly, as in the last option, is allowed.
  4. 4. What is [...['a' => 1, 'b' => 2], ...['b' => 3]] in PHP 8.1 and later?

    Since PHP 8.1 string keys are kept and a later duplicate overwrites the earlier one, exactly like array_merge().
  5. 5. What does print_r([...[3 => "x", 7 => "y"]]); show for keys?

    Spreading renumbers integer keys from 0, the same way array_merge() does.

Summary

  • [$a, $b] = $array; assigns elements with keys 0, 1, โ€ฆ to variables. Leave gaps to skip elements. list() is the older spelling.
  • A missing key gives an "Undefined array key" warning and null, just like reading $array[2] directly.
  • Keyed destructuring, ['name' => $name] = $row;, picks values by key in any order. One bracket level can't mix keyed and unkeyed entries.
  • Destructuring swaps variables ([$a, $b] = [$b, $a]), unpacks multiple return values, nests to match nested data, and works in foreach heads.
  • &$var in a pattern binds a reference (PHP 7.3+); use it rarely.
  • [...$a, ...$b] spreads arrays and Traversables into a new array. Integer keys are renumbered; string keys (PHP 8.1+) are kept, later values winning, the same as array_merge(). The + operator keeps the first value instead.
  • f(...$args) unpacks an array into arguments; string keys become named arguments (PHP 8.1+).

Next: Object-Oriented Programming in PHP