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.

One thought on “PHP: What is More Powerful Than list() – Perhaps extract()

  1. Extract just adds incomprehension to code, you don’t know what variables were created, whether old ones were overwritten etc. It’s the last thing you want to do.

Leave a Reply

Your email address will not be published. Required fields are marked *