What is array destructuring in PHP, and how does the list function or short array syntax simplify extracting values from an array?
Short answer
Array destructuring lets you assign multiple array elements directly to individual variables in a single statement, using either the list function or the equivalent shorthand square bracket syntax, which is especially convenient when a function returns multiple related values as…
Advertisement
AModel answer
Array destructuring lets you assign multiple array elements directly to individual variables in a single statement, using either the list function or the equivalent shorthand square bracket syntax, which is especially convenient when a function returns multiple related values as an array and you want to immediately assign each value to its own clearly named variable.
[$name, $age] = ['Ali', 30];
echo "$name is $age years old";Real-world example
A function that calculates both the width and height of an image returns them as an array, and the calling code immediately destructures that array into two clearly named variables for easy use afterward.
Likely follow-ups
- Can you skip specific elements when destructuring an array?
- Does destructuring work with associative arrays as well as indexed arrays?
Related topics