Magic list()

list() - is a very interesting PHP construct.
Let's read the man:

list — Assign variables as if they were an array
Description
void list ( mixed $varname, mixed $... )

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

So, the usage may be as following:

$a = array(1,2,3,4,5,);//yes, yes, last comma is completely correct for php array
list($b, $c, $d) = $a;

echo $b.'-'.$c.'-'.$d;

Outputs:
1-2-3

sure.

And now a little trick. Look:

$a = array(1,2,3,4,5,);//yes, yes, last comma is completely correct for php array
list(, $b, $c, $d) = $a;

echo $b.'-'.$c.'-'.$d;

Outputs:
2-3-4

OK, where should I use it?
First idea - ugly functions like imagettfbbox()
Take a look:

Return Values

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:
0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position

So, you can make code better using list here. For example:

list($left_x,$bottom_y,$right_x, , ,$top_y) = imagettfbbox($some, $params, $here, $as, $usual);

Generally, it allows to extract and rename few needed variables from an array you don't need.

Here is something to think about:

$a = array(1,2,3,4,5,);
list($b[], $b[], $c, $d) = $a;

print_r($b);
echo $b.'-'.$c.'-'.$d;

This outputs:
Array ( [0] => 2 [1] => 1 ) Array-3-4

Take a look at the array $b elements: they are ordered vice versa

and if we will write

list($b[0], $b[1], $c, $d) = $a;

instead of corresponding line, we will get
Array ( [1] => 2 [0] => 1 ) Array-3-4

Seems like arguments are stored in opposite order somewhere...

Leave a Reply