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

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

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.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}