downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  

<ksortnatcasesort>
Last updated: Thu, 26 Jun 2008

list

(PHP 4, PHP 5)

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.

Parameters

varname

A variable.

Return Values

No value is returned.

Examples

Example #1 list() examples

<?php

$info
= array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo
"$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo
"$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo
"I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Example #2 An example use of list()

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php

$result
= mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list(
$id, $name, $salary) = mysql_fetch_row($result)) {
   echo
" <tr>\n" .
        
"  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
        
"  <td>$salary</td>\n" .
        
" </tr>\n";
}

?>

</table>

Example #3 Using nested list()

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>
int(1)
int(2)
int(3)

Example #4 Using list() with array indices

<?php

$info
= array('coffee', 'brown', 'caffeine');

list(
$a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

Notes

Warning

list() assigns the values starting with the right-most parameter. If you are using plain variables, you don't have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn't. It's assigned in the reverse order.

Note: list() only works on numerical arrays and assumes the numerical indices start at 0.



add a noteadd a note User Contributed Notes
Assign variables as if they were an array
There are no user contributed notes for this page.




<ksortnatcasesort>
Last updated: Thu, 26 Jun 2008
show source | credits | sitemap | contact | advertising | mirror sites
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://phpbuilder.com/
Last updated: Tue Nov 1 20:20:59 2005 EST
Columns / Articles | Tips / Quickies | News | News Linking and RSS Feeds | Shared Code Library
Mail Archives | Support / Discussion Forums | Get Started! Links | Contribute! | Docs