Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 922
rsk82 Avatar asked Dec 04 '11 22:12

rsk82


3 Answers

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...

like image 104
K-Gun Avatar answered Oct 23 '22 11:10

K-Gun


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);
like image 44
landons Avatar answered Oct 23 '22 11:10

landons


What about using array_values()?

<?php
   list($fruit1, $fruit2) = array_values( array('fruit1'=>'apples','fruit2'=>'oranges') );
?>
like image 50
Broom Avatar answered Oct 23 '22 11:10

Broom