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

PhpArraysListAssociative Array

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

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

What about using array_values()?

<?php
   list($fruit1, $fruit2) = array_values( array('fruit1'=>'apples','fruit2'=>'oranges') );
?>

Solution 4 - Php

It's pretty straightforward to implement.

function orderedValuesArray(array &$associativeArray, array $keys, $missingKeyDefault = null)
{
    $result = [];
    foreach ($keys as &$key) {
        if (!array_key_exists($key, $associativeArray)) {
            $result[] = $missingKeyDefault;
        } else {
            $result[] = $associativeArray[$key];
        }
    }
    return $result;
}
$arr = [
    'a' => 1,
    'b' => 2,
    'c' => 3
];
list($a, $b, $c) = orderedValuesArray($arr, ['a','AAA', 'c', 'b']);
echo $a, ', ', $b, ', ', $c, PHP_EOL;

output: 1, , 3

  • less typing on usage side
  • no elements order dependency (unlike array_values)
  • direct control over variables names (unlike extract) - smaller name collision risk, better IDE support

Solution 5 - Php

If you are in my case:

list() only works on numerical array. So if you can, leaving blank in fetch() or fetchAll() -> let it have 2 options: numerical array and associative array. It will work.

Solution 6 - Php

consider this an elegant solution:

<?php

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

    foreach ($fruits as $key => $value)  
    {
        $$key = $value;  
    }
    echo $fruit1; //=apples  

?>

Solution 7 - Php

<?php

function array_list($array)
{
    foreach($array as $key => $value)
    $GLOBALS[$key] = $value;
}

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

array_list($array);

echo $fruit1; // oranges


?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrsk82View Question on Stackoverflow
Solution 1 - PhpK-GunView Answer on Stackoverflow
Solution 2 - PhplandonsView Answer on Stackoverflow
Solution 3 - PhpBroomView Answer on Stackoverflow
Solution 4 - PhpAlexander MalakhovView Answer on Stackoverflow
Solution 5 - PhpTrung PhạmView Answer on Stackoverflow
Solution 6 - Phpkrommer_bView Answer on Stackoverflow
Solution 7 - PhpDejan MarjanovićView Answer on Stackoverflow