PHP 8 Beginner Language Basics · 6 min read

PHP Array Destructuring

Lesson 39 of 43 in the PHP 8 learning path.

How do I unpack the first two lessons from a list?

[] on the left of an assignment pulls values out of an array by position or by key.

A long chain of $row[0] and $row[1] hides which value is the title and which is the track.

Syntax & Parameters

Syntax
[$first, $second] = $titles;

Example

src/Pair.php
<?php
declare(strict_types=1);
function lead(array $titles): string
{
    if (count($titles) < 2) {
        throw new InvalidArgumentException('Need two titles.');
    }
    [$first, $second] = $titles;
    return $first . ' then ' . $second;
}
echo lead(['Routes', 'Queries', 'Blade']), PHP_EOL;
$row = ['title' => 'Routes', 'track' => 'php'];
['title' => $title, 'track' => $track] = $row;
echo $title, ' ', $track, PHP_EOL;

Expected Output

Routes then Queries
Routes php

Line-by-Line Walkthrough

  1. The function requires at least two titles.
  2. The short list syntax assigns index 0 and 1.
  3. Later items are ignored.
  4. The string names the order.
  5. The associative form matches keys, not positions.
  6. title and track are pulled by name.
  7. A missing key warns and leaves the variable null.
  8. Check the length before you unpack a positional pair.

Common Pitfalls & Security

Check the edge before you ship it.

  • Unpacking a short array warns on the missing index.
  • Key order in the pattern does not reorder the source.
  • Skipping with commas, [, $second], is easy to misread.
  • Destructuring does not copy nested arrays deeply.

Best Practices & Modern Standards

Unpack when the positions or keys are part of the contract.

Guard the length for positional pairs.

Real-World Use

A homepage teaser takes the first two published titles and prints them as a sequence without a manual index dance.

Frequently Asked Questions

Does this remove items from the array?

No. It only reads them into variables.

Can I unpack by key?

Yes. Use the ['title' => $title] form.

What if a key is missing?

PHP warns and the variable is null. Check the keys you require.

Is list() the same?

list() is the older spelling of the positional form. The [] syntax is the one to write.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…