Can PHP's list() work with associative arrays?

rsk82 picture rsk82 · Dec 4, 2011 · Viewed 21.5k times · Source

Example:

list($fruit1, $fruit2) = array('apples', 'oranges');

code above of course works ok, but code below:

list($fruit1, $fruit2) = array('fruit1' => 'apples', 'fruit2' => 'oranges');

gives: Notice: Undefined offset: 1 in....

Is there any way to refer to named keys somehow with list like list('fruit1' : $fruit1), have you seen anything like this planned for future release?

Answer

K-Gun picture K-Gun · Dec 21, 2016

With/from PHP 7.1;

$array = ['fruit1' => 'apple', 'fruit2' => 'orange'];

// [] style
['fruit1' => $fruit1, 'fruit2' => $fruit2] = $array;

// list() style
list('fruit1' => $fruit1, 'fruit2' => $fruit2) = $array;

print $fruit1; // apple