Skip to content

PHP Tutorial Arrays

Destructuring Arrays

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

Destructuring pulls values out of an array into separate variables in one step.

index.php
PHP
<?php
$point = [10, 20];

[$x, $y] = $point;

echo "x=$x, y=$y";
Output
OUTPUT
x=10, y=20

Without it, you would write $x = $point[0]; $y = $point[1];.

Skip items

Leave a gap with an empty slot.

index.php
PHP
<?php
[$first, , $third] = ["a", "b", "c"];

echo $first . $third;
Output
OUTPUT
ac

With keys

For an associative array, name the keys you want.

index.php
PHP
<?php
$user = ["name" => "Isha", "city" => "Kochi", "age" => 29];

["name" => $name, "city" => $city] = $user;

echo "$name from $city";
Output
OUTPUT
Isha from Kochi

Nested arrays

index.php
PHP
<?php
$data = ["Ravi", [28, "Pune"]];

[$name, [$age, $city]] = $data;

echo "$name, $age, $city";
Output
OUTPUT
Ravi, 28, Pune

In a foreach loop

This is where destructuring saves the most space.

index.php
PHP
<?php
$products = [
    ["Pen", 12],
    ["Book", 250],
];

foreach ($products as [$name, $price]) {
    echo "$name costs $price\n";
}
Output
OUTPUT
Pen costs 12
Book costs 250

With keys:

index.php
PHP
<?php
$users = [
    ["id" => 1, "name" => "Ana"],
    ["id" => 2, "name" => "Ben"],
];

foreach ($users as ["id" => $id, "name" => $name]) {
    echo "#$id $name\n";
}
Output
OUTPUT
#1 Ana
#2 Ben

Return several values from a function

index.php
PHP
<?php
function splitName(string $full): array
{
    return explode(" ", $full, 2);
}

[$first, $last] = splitName("Ada Lovelace");

echo "$last, $first";
Output
OUTPUT
Lovelace, Ada

Swap two variables

index.php
PHP
<?php
$a = 1;
$b = 2;

[$a, $b] = [$b, $a];

echo "$a $b";
Output
OUTPUT
2 1

Missing items

If the array has fewer items than you ask for, PHP gives null plus a warning.

index.php
PHP
<?php
[$a, $b] = [1];

var_dump($b);
Output
OUTPUT
Warning: Undefined array key 1 in /path/to/index.php on line 2
NULL

list() is the older form

list($a, $b) = $array; does the same as [$a, $b] = $array;. You will meet it in old code. Use the square brackets in new code.

lightbulb
Name things as you unpack
[$lat, $lng] = $coordinates; documents the meaning of each position right where you use it.