Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Array destructuring in PHP

Folks who are familiar with the JavaScript’s ES6 may very well aware of the destructuring feature which allows us to extract data from arrays, objects, maps and sets. For instance, Using ES6 way, we can assign the top level variables of the objects to local variables using destructuring like below:

const Car = {
    color: 'blue',
    type: 'sedan'
}

const {color, type} = Car;

So, color and type has been assigned the variables from the Car object respectively. This is how object destructuring is achieved in JavaScript. What about PHP?

PHP >=7.1 has introduced associative array destructuring along with the list destructuring which was present in the earlier versions of PHP. Let’s take a very simple example. For earlier versions than 7.1, to assign the array values to the variables, you’d achieve using list() like this:

list($dog, $cat, $cow) = $animals;

But from version 7.1, you can just use shorhand array syntax([]) to achieve the same:

[$dog, $cat, $cow] = $animals;

As you can see, it’s just more cleaner and expressive now, just like ES6. Another area where you can use Array destructuring is in loops.

$data = [
    [1, 'Foo'],
    [2, 'Bar']
]

foreach ($data as [$id, $name]) {
    // logic here with $id and $name
}

If you want to be specific about the key you assign to the variable, you can do it like this:

foreach ($data as ['uid' => $id, 'fname' => $name]) {
    // logic here with $uid and $fname
}

Wrapping up

Although, we have ‘list()’ already, utilizing the shorthand array syntax for destructuring is just more cleaner way and makes more sense.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?