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”?

$array = [1, 2, 3];

// Using the list syntax:

list($a, $b, $c) = $array;

The shorthand is quite handy:

[$a, $b, $c] = $array;

//Or with named/non-numeric keys

['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,

['c' => $c_newName, 'a' => $a_newName] = $array;

Leave a Reply