Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array unpacking: spread and destructuring

How PHP unpacks arrays: the spread operator with string keys (PHP 8.1), list() and [] destructuring by key, nesting, skipping, swapping and foreach destructuring.

PHP can take arrays apart and put them back together with two pieces of syntax. Destructuring ([$a, $b] = $array or list(...)) copies elements into variables. The spread operator (...$array) expands an array inside another array literal or an argument list.

Both work with string keys in modern PHP: destructuring has supported keys since PHP 7.1, and spreading arrays with string keys inside array literals since PHP 8.1. This page focuses on that key behavior; the basics of list and the spread operator have their own pages.

PHP
<?php
['id' => $id, 'name' => $name] = ['id' => 7, 'name' => 'Ana'];
$merged = [...['a' => 1], ...['b' => 2]];

Try it

PHP Destructuring by position and by key

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.

PHP Spread and 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.

Rules in detail

Destructuring

  • A pattern with no keys reads positions 0, 1, 2, .... Leave a slot empty to skip an element.
  • A pattern with keys reads exactly those keys. You cannot mix keyed and unkeyed entries in one pattern.
  • A key that does not exist raises a warning (Undefined array key) and assigns null. Provide defaults with ?? on a separate line, or check with isset() first.
  • Patterns can be nested, can assign to array elements and properties ([$this->a, $this->b] = $pair), and can take references with &.
  • list() and [] are the same thing. The short form is the usual choice.

Spread inside array literals

  • Works with arrays and any Traversable (PHP 7.4 and later).
  • Integer keys are renumbered, while string keys are kept and later values overwrite earlier ones. Before PHP 8.1, spreading an array with string keys raised an error.
  • Spread elements and ordinary elements can be mixed freely, and the order you write is the order you get.

Usage notes

  • Destructuring never changes the source array; it copies values.
  • Spread is not recursive, so nested arrays are copied as they are. Use array_merge_recursive() for deep merges.
  • [...$a, ...$b] versus +: spread lets the later array win on string keys, the + operator keeps the left value.
  • Performance: spreading is as fast as array_merge(); avoid spreading huge arrays in a loop (it copies each time).