Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

PHP: What is More Powerful Than list() – Perhaps extract()

DZone's Guide to

PHP: What is More Powerful Than list() – Perhaps extract()

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

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.

#1 for location developers in quality, price and choice, switch to HERE.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}