Can PHP's list() work with associative arrays?
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?
Solution 1:
With/from PHP 7.1:
For keyed arrays;
$array = ['fruit1' => 'apple', 'fruit2' => 'orange'];
// [] style
['fruit1' => $fruit1, 'fruit2' => $fruit2] = $array;
// list() style
list('fruit1' => $fruit1, 'fruit2' => $fruit2) = $array;
echo $fruit1; // apple
For unkeyed arrays;
$array = ['apple', 'orange'];
// [] style
[$fruit1, $fruit2] = $array;
// list() style
list($fruit1, $fruit2) = $array;
echo $fruit1; // apple
Note: use []
style if possible by version, maybe list goes a new type in the future, who knows...
Solution 2:
EDIT: This approach was useful back in the day (it was asked & answered nine years ago), but see K-Gun's answer below for a better approach with newer PHP 7+ syntax.
Try the extract()
function. It will create variables of all your keys, assigned to their associated values:
extract(array('fruit1' => 'apples', 'fruit2' => 'oranges'));
var_dump($fruit1);
var_dump($fruit2);
Solution 3:
What about using array_values()?
<?php
list($fruit1, $fruit2) = array_values( array('fruit1'=>'apples','fruit2'=>'oranges') );
?>