Programming Tutorials

(追記) (追記ここまで)

Using list() in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008年11月22日 [フレーム]

The list() construct is a way of assigning multiple array offsets to multiple variables in one statement:

list($var1, $var2, ...) = $array;

The first variable in the list is assigned the array value at offset 0, the second is assigned offset 1, and so on. Therefore, the list() construct translates into the following series of PHP statements:

$var1 = $array[0];
$var2 = $array[1];
...

The indexes 0 and 1 returned by each() are used by the list() construct. You can probably already guess how the combination of list() and each() work.

Consider the highlighted line from the previous $players traversal example:

$players = array("John", "Barbara", "Bill", "Nancy");
reset($players);
while (list($key, $val) = each($players)) {
print "#$key = $val\n";
}

What happens in the boldfaced line is that during every loop iteration, each() returns the current position's key/value pair array, which, when examined with print_r(), is the following array:

Array
(
[1] => John
[value] => John
[0] => 0
[key] => 0
)

Then, the list() construct assigns the array's offset 0 to $key and offset 1 to $val.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /