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

submit to reddit

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.

Related posts:

  1. PHP: What is More Powerful Than list()
  2. Construct a Sorted PHP Linked List
  3. Thing to Know About PHP Arrays

You are a GREAT developer? Click here to answer the weekly quiz!

This entry was posted in micro tutorial, PHP and tagged , , , , , , , , , . Bookmark the permalink.

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

  1. rav says:

    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 *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">