Array Destructuring With or Without List Function in PHP

Have you been unwillingly using the useful “extract” function to convert array elements into their corresponding names with same variable name as the key of the array element? Have you been worrying about the non-friendly nature of your code for new developers while using the extract function? Here is a shorthand for the rescue for Array Destructuring.

Remember to list elements in conventional way with old friend “list”?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$array = [1, 2, 3];
$array = [1, 2, 3];
$array = [1, 2, 3];

// Using the list syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
list($a, $b, $c) = $array;
list($a, $b, $c) = $array;
list($a, $b, $c) = $array;

The shorthand is quite handy:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[$a, $b, $c] = $array;
[$a, $b, $c] = $array;
[$a, $b, $c] = $array;

//Or with named/non-numeric keys

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
['c' => $c, 'a' => $a] = $array;
['c' => $c, 'a' => $a] = $array;
['c' => $c, 'a' => $a] = $array;

This (the last one in particular) is more transparent way as compare to “extract” function. The plus point is that you can change the variable name for extracted value. For example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
['c' => $c_newName, 'a' => $a_newName] = $array;
['c' => $c_newName, 'a' => $a_newName] = $array;
['c' => $c_newName, 'a' => $a_newName] = $array;

Leave a Reply