PHP list() and Shorthand for Array Destructuring

PHP construct list() or its shorthand can be useful in many cases. It can be very useful to use it with PHP functions that returns arrays. Supun Kavinda have interesting article about.

<?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;
  • Takes the ‘meta’ key and saves its value in $meta which is now an array with two keys; opened and soap-types
  • Takes ‘isAvailableInStore’ key and instead of saving its value in a variable, we break its value again into variables. (Nested destructuring)

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)

https://supunkavinda.blog/php-list

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.