55

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?

1

7 Answers 7

99

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

0
52

EDIT: This approach was useful back in the day (it was asked & answered nine years ago), but see Kerem'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);
16
  • 1
    Yes, this works. On the other hand, it is almost always good practice to supply a prefix when using extract unless you are 100% absolutely certain which keys will be present. Dec 4, 2011 at 22:25
  • 1
    Yes, I'd run it with array_intersect_key() first with expected keys.
    – landons
    Dec 4, 2011 at 22:29
  • 3
    @Jurik, have you tried using list() with array_values()? You're right though--that function is weird.
    – landons
    May 13, 2014 at 14:56
  • 15
    Please don't use extract. IDEs can't handle it. And it can create a host of other problems.
    – peter
    Oct 8, 2015 at 19:05
  • 1
    @Bananaapple, I've edited my answer accordingly. I may be biased, but I'm not sure downvoting answers that were true at the time is necessarily the right approach. Thanks for calling it to my attention though.
    – landons
    Jan 2, 2019 at 22:46
50

What about using array_values()?

<?php
   list($fruit1, $fruit2) = array_values( array('fruit1'=>'apples','fruit2'=>'oranges') );
?>
4
  • 1
    This method is better (then accepted answer) if you want to skip some keys Aug 25, 2014 at 10:58
  • 4
    This does not work if the values in the array are in reverse order, like array('fruit2'=>'apples','fruit1'=>'oranges'). The value of 'fruit2' is assigned $fruit1 and vice versa.
    – jonasfh
    Mar 30, 2016 at 9:08
  • PHP 7.1 offers a cleaner way - see K-Gun's answer instead. Dec 5, 2018 at 9:19
  • This works great for using older version of IDE such as PhpStorm 10.0.4 .
    – John Wong
    Jan 30 at 8:53
0

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
2
  • I see no benefit to making $key modifiable in the foreach() -- you never attempt to modify it. May 13, 2022 at 15:00
  • @mickmackusa, I haven't programmed in PHP since 2017, but I think I did that to ensure $key isn't copied. Can't tell for sure at this point if that was my intention, or if that actually makes any technical difference. May 13, 2022 at 16:51
0

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.

0
-3

consider this an elegant solution:

<?php

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

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

?>
2
  • 2
    Sorry, but in reality variable variables are almost never the "elegant" solution.
    – Kzqai
    Jun 3, 2014 at 14:47
  • 1
    So why not using extract()? It basically does what you're solution is providing
    – Ali Alwash
    Apr 5, 2015 at 12:35
-5
<?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


?>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.