PHP: What is More Powerful Than list() – Perhaps extract()
list() in PHP
Recently I wrote about list() in PHP which is indeed very powerful when assigning variable values from array elements.
$a = array(10, array('here', 'are', 'some', 'tests'));
list($count, $list) = $a;Actually my example in the post was not correct, because I wrote that
you can pass an associative array, but the truth is that you cannot,
and thus the array should be always with numeric keys. After noticing
the comments of that post, and thanks to @Philip, I searched a bit
about how this problem can be overcome.
There is a Solution
As always PHP gives a perfect solution! You can see on the list() doc page that there is a function that may help you use an associative array.
Extract
extract() is perhaps less known than list(), but it does the right thing!
$a = array('count' => 10, 'list' => array('here', 'are', 'some', 'tests'));
extract($a);
echo $count; // 10
print_r($list); // array('here'....Note that now both $count and $list are defined.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


