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.

Support for keys in list(), or its new shorthand syntax [] in PHP

Now as of PHP 7.1, you can define the keys of your array that will be parsed when destructuring your arrays. Prior to PHP 7.1, you could only use arrays with numeric indexes. Now with this new addition, our lives just got easier.

Let’s go over a few examples below on how we can use this new feature.

Example

Let’s start by setting up our array.

<?php

$people = [
    [
        'id' => 1,
        'age' => 29,
        'name' => 'Frank',
    ],
    [
        'id' => 2,
        'age' => 28,
        'name' => 'Sarah',
    ],
    [
        'id' => 3,
        'age' => 27,
        'name' => 'Michael',
    ],
];

Now that we have our array setup, we’ll want to start by destructuring the first person in the array.

<?php

$person = $people[0]; // Gets the first person

list('id' => $id, 'name' => $name, 'age' => $age) = $person;

echo 'ID: ' . $id . '<br>';
echo 'Name: ' . $name . '<br>';
echo 'Age: ' . $age . '<br>';

You’ll notice that I was able to specify the keys above, and also that they do not need to be in the same order as the original array. Since our keys match up with the keys in our array, our application is now smart enough to handle that.

Let’s rewrite the above to use the shorthand syntax now.

<?php

$person = $people[0]; // Gets the first person

['id' => $id, 'name' => $name, 'age' => $age] = $person;
echo 'ID: ' . $id . '<br>';
echo 'Name: ' . $name . '<br>';
echo 'Age: ' . $age . '<br>';