PHP list() and Shorthand for Array Destructuring


<?php
$profile = ['James', 25, 'MIT'];

Your profile data is stuck in an indexed array ($profile). You know that each index is your name, age and the university respectively. So, now, you are going to break it into 3 variables for ease.


$name = $profile[0];
$age = $profile[1];
$uni = $profile[2];

Okay, if you had 5 variables, 5 lines. We need a better solution!

list() function language construct

list() is a language construct in PHP, which can be used for array destructuring.

Array destructuring is breaking an array into variables

<?php
list($name, $age, $uni) = $profile;

// $name = 'James'
// $age = 25
// $uni = 'MIT'

That's the beauty of list()! It takes an array, then pulls out variables from it.

But, be careful! If the third item (2nd index) is missing in the array, PHP will show a notice. Therefore, make sure array elements are not missing before using list()

list()'s Shorthand

[] is the shorthand for list(). But, wait! It's the array construct?


[$name, $age, $uni] = $profile;

Since PHP 7.1, if you use [] before the assignment operator (=), it will be considered as the shorthand for list(). It makes the PHP programmer's life easier, but with a confusion of that, it can be ambiguous with the shorthand array syntax. It's up to you to choose the best one. ([] fits very well for me ;)

Destructuring Associative Arrays?

(Note that it's destructuring, not destructing. Remember that as de-structuring. We change the structure.)

We can destructure associative arrays as follows.


<?php
$profile = [
    'name' => 'James',
    'age' => 25,
    'university' => 'MIT'
];
['name' => $name, 'age' => $age, 'university' => $uni] = $profile;
echo $name; // James

Here we can assign each key to a variable. Make sure all the keys are in the array as PHP will show a notice if a key is not defined. This type of destructuring can be useful when fetching data from the database. Here's an example.


$result = $mysqli -> query('SELECT name, email, password FROM users WHERE id = 1 LIMIT 1');
$result = $result -> fetch_assoc();

['name' => $name, 'email' => $email, 'password' => $pwd] = $result;
echo $name;
echo $email;
echo $pwd;

Nested Destructuring

As a programmer, you will deal with nested (or multi-dimensional) arrays very often. Most of JSON-based APIs return nested data as it's very easy to share and understand. Hopefully, PHP allows nested destructuring for multi-dimensional arrays.

Here's some data from our "Soap Shop"


<?php
$soapShop = [
    'meta' => [
        'opened' => true,
        'soap-types' => ['Glycerin', 'Transparent', 'Liquid']
    ],
    'isAvailableInStore' => [
        'Glycerin' => true,
        'Transparent' => true,
        'Liquid' => false
    ]
];

Let's break it into variables.


[
    'meta' => $meta,
    'isAvailableInStore' => [
        'Glycerin' => $glycerinSoapAvailable,
        'Transparent' => $transparentSoapAvailable,
        'Liquid' => $liquidSoapAvailable
    ]
] = $soapShop;

That's quite interesting right?

Loooooooooops!

This is a superpower of PHP! I use array destructuring very often when looping through a simple array.


<?php
$people = [
    [
        'name' => 'John',
        'age' => 20
    ],
    [
        'name' => 'Callum',
        'age' => 17
    ]
];
// the old way
/* 
foreach ($people as $person) {
    echo $person['name'];
    echo $people['age'];
}
*/
foreach ($people as ['name' => $name, 'age' => $age]) {
    echo $name;
    echo $age;
}

Here's an example usage of array destructuring in an array of indexed arrays


<?php
$array = [
    [1,2,3],
    [4,2,5],
    [2,6,4]
];
foreach ($array as [$a, $b, $c]) {
    echo $a   $b   $c;
}

list() or its shorthand can be useful in many cases. It can be very useful to use it with PHP functions that returns arrays. (Ex: parse_url, pathinfo, or user-defined functions)

Thank you for reading!

Tagged: PHP
Liked the article? Follow me on Twitter, or help Hyvor grow by funding Hyvor Talk.
Latest on Hyvor Developer
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
Image for Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image for PHP Contact Form - The Email Method
PHP Contact Form - The Email Method
Image for The Best Way to Perform MYSQLI Prepared Statements in PHP
The Best Way to Perform MYSQLI Prepared Statements in PHP
Related Articles
2491