Destructuring arrays in PHP: Practical examples

Being more focussed on JavaScript nowadays, I kinda forgot that it’s possible to destructure arrays in PHP ever since the release of PHP 7.1. Frank de Jonge provides us with some practical examples such as this simple one:

// JavaScript
let options = {enabled: true, compression: 'gzip'};  
let { enabled, compression } = options;

console.log(enabled);
console.log(compression);
// PHP 7.1+
$options = ['enabled' => true, 'compression' => 'gzip'];
['enabled' => $enabled, 'compression' => $compression] = $options;

var_dump($enabled);
var_dump($compression);

Freek Van der Herten adds some extra examples, showing its use in for loops:

$members = [
    [1, 'Seb'],
    [2, 'Alex'],
    [3, 'Brent'],
];

foreach ($members as [$id, $name]) {
   // do stuff with $id and $name
}

Array destructuring in PHP →
Array destructuring in PHP (Additions by Freek) →

About the Author

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

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.