phparrayslistvariablesvariable-assignment

PHP multi-variables assignment for "key => value" array


PHP's list keyword is nice for taking out variables from an array $a as below:

    $a = array(1,22);
    list($b, $c) = $a;
    var_dump("$a $b $c");

But for array $a2 in the form of key => value as below, I failed to use list:

    $a2 = array('b'=>1,'c'=>22);
    list($b, $c) = $a2;
    list($bkey, $b, $ckey, $c) = $a2;
    list( list($bkey, $b), list($ckey,$c) ) = $a2;
    
    var_dump("$a2 $b $c");

All of the three above assignments fail.

How can I get the key & value in array $a2?


Solution

  • It does not seem to work with associative arrays, you can do something like this though:

    foreach ($array as $key => $value) {
         $$key = $value;
    }
    

    Example:

    $a2 = array('b'=>1,'c'=>22);
    foreach ($a2 as $key => $value) {
         $$key = $value;
    }
    
    echo $b . '<br>';
    echo $c;
    

    Result:

    1
    22
    

    One could also use extract() function but I generally avoid it because using it on user-inputted values could create security hazards. Depending on your choice, you might want to use it or if data isn't coming from the user's side.