Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2024 by Frank Perez.

Symmetric Array Destructuring in PHP

As of PHP 7.1, you can now use the shorthand array syntax to destructure your arrays for assignment. Previously you would have had to use a function like list, but now you can use the simple new array shorthand syntax.

Let’s look at some examples.

Basic Example

<?php

$names = [
    'Frank Perez',
    'Carmella Osman',
    'Kristina Endo',
];

// New Shorthand Syntax
[$firstName, $lastName] = $names[0];

// Previous list() Syntax
list($firstName, $lastName) = $names[0];

Example Using Loops

<?php

$names = [
    'Frank Perez',
    'Carmella Osman',
    'Kristina Endo',
];

$names = array_map(function($name) {
    return explode(' ', $name);
}, $names);

foreach($names as [$firstName, $lastName]) {
    echo $lastName . ', ' . $firstName . '<br>';
}