list

(PHP 3, PHP 4, PHP 5)

list --  Присвоить переменным из списка значения подобно массиву

Описание

void list ( mixed varname, mixed ... )

Подобно array(), это не функция, а языковая конструкция. list() используется для того, чтобы присвоить списку переменных значения за одну операцию.

Замечание: list() работает только с массивами, индексами которых являются числа и нумерация которых начинается с 0.

Пример 1. Примеры использования list()

<?php

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

// Составить список всех переменных
list($drink, $color, $power) = $info;
echo
"$drink is $color and $power makes it special.
"
;

// Составить список только некоторых из них
list($drink, , $power) = $info;
echo
"$drink has $power.
"
;

// Или только третья
list( , , $power) = $info;
echo
"I need $power!
"
;

?>

Пример 2. Пример использования 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>
"
.
        
"  <td><a href=\"info.php?id=$id\">$name</a></td>
"
.
        
"  <td>$salary</td>
"
.
        
" </tr>
"
;
}

?>

</table>

Внимание

list() присваивает значения начиная с крайнего правого параметра. Если вы используете простые переменные, можете не беспокоиться об этом. Но если вы используете индексные массивы, вы можете ожидать, что в результате выполнения функции list() вы получите тот же порядок элементов, что и в исходном массиве: слева направо; однако это не так. Они будут присвоены в обратном порядке.

Пример 3. Использование list() с индексами массивов

<?php

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

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

var_dump($a);

?>

Выведет (сравните порядок исходных элементов с порядком, в в котором они были перезаписаны функцией list()):

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

См. также each(), array() и extract().



list
ergalvan at bitam dot com
04-May-2006 11:29
With regard to the note written by dolan at teamsapient dot com:

You must take note that list() assigns variables starting from the rightmost one (as stated in the warning). That makes $record having the value "value4" and then $var1, $var2 and $var3 take their values from the "new" $record variable.

It's clear that the behavior stated in the warning wasn't followed by version 5.0.4 (and perhaps previous versions?)
dolan at teamsapient dot com
06-Apr-2006 11:08
I noticed w/ version 5.1.2, the behavior of list() has changed (this occurred at some point between version 5.0.4 and 5.1.2).  When re-using a variable name in list() that list() is being assigned to, instead of the values being assigned all at once, the reused variable gets overwritten before all the values are read.

Here's an example:
** disclaimer: obviously this is sloppy code, but I want to point out the behavior change (in case anyone else comes across similar code) **

<?
$data
= array();
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");

foreach(
$data as $record)
{
   list(
$var1, $var2, $var3, $record) = $record;
   echo
"var 1: $var1, var 2: $var2, var 3: $var3, record: $record\\n";
}
?>

OUTPUT on version 5.0.4:
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4

OUTPUT on version 5.1.2:
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
mzizka at hotmail dot com
02-Jan-2006 08:49
Elements on the left-hand side that don't have a corresponding element on the right-hand side will be set to NULL. For example,

<?php
$y
= 0;
list(
$x, $y) = array("x");
var_dump($x);
var_dump($y);
?>

Results in:

string(1) "x"
NULL
Nearsighted
25-Jul-2005 07:34
list, coupled with while, makes for a handy way to populate arrays.

while (list($repcnt[], $replnk[], $date[]) = mysql_fetch_row($seek0))
{
// insert what you want to do here.
}

PHP will automatically assign numerical values for the array because of the [] signs after the variable.

From here, you can access their row values by array numbers.

eg.

for ($i=0;$i<$rowcount;$i++)
{
echo "The title number $repcnt[$i] was written on $date[$i].";
}
webmaster at miningstocks dot com
31-May-2005 11:05
One way to use the list function with non-numerical keys is to use the array_values() function

<?php
$array
= array ("value1" => "one", "value2" => "two");
list (
$value1, $value2) = array_values($array);
?>
php at keithtyler dot com
12-May-2005 02:27
Note to perl programmers, this does NOT work like Perl's anonymous-list technique. It will discard any elements on the right hand side that do not have a corresponding recipient value on the left hand side.

In Perl, you can put an array at the end of the list, and it will pick up all remaining elements from the right hand of the assignment.

($val1,$val2,@others)=array("a","b","c","d","e")

will result in $val1="a", $val2="b", and @others=("c","d","e").

This cannot seem to be done in PHP, even if you declare the array beforehand:

$others=Array();
list($val1,$val2,$others)=array("a","b","c","d","e")

will result in $val1="a", $val2="b", and $others="c". Note also that $others is redefined as whatever type the right-hand side value was, and is no longer an Array.

This is in 4.3.11.
mortoray at ecircle-ag dot com
16-Feb-2005 01:29
There is no way to do reference assignment using the list function, therefore list assignment is will always be a copy assignment (which is of course not always what you want).

By example, and showing the workaround (which is to just not use list):

   function &pass_refs( &$a ) {
       return array( &$a );
   }

   $a = 1;
   list( $b ) = pass_refs( $a ); //*
   $a = 2;
   print( "$b" ); //prints 1

   $ret = pass_refs( $a );
   $b =& $ret[0];
   $a = 3;
   print( "$b" ); //prints 3

*This is where some syntax like the following would be desired:
   list( &$b ) = pass_refs( $a );
or maybe:
   list( $b ) =& pass_refs( $a );
jennevdmeer at zonnet dot nl
21-Oct-2004 08:29
This is a function simulair to that of 'list' it lists an array with the 'key' as variable name and then those variables contain the value of the key in the array.
This is a bit easier then list in my opinion since you dont have to list up all variable names and it just names them as the key.

<?php
 
function lista($a) {
  foreach (
$a as $k => $v) {
  
$s = "global \$".$k;
   eval(
$s.";");
  
$s = "\$".$k ." = \"". $v."\"";
   eval(
$s.";");
  }
 }
?>
HW
14-Aug-2004 01:08
The list() construct can be used within other list() constructs (so that it can be used to extract the elements of multidimensional arrays):
<?php
$matrix
= array(array(1,2),
               array(
3,4));

list(list(
$tl,$tr),list($bl,$br)) = $matrix;

echo
"$tl $tr $bl $br";
?>
Outputs "1 2 3 4".
jeronimo at DELETE_THIS dot transartmedia dot com
28-Jan-2004 07:28
If you want to swap values between variables without using an intermediary, try using the list() and array() language constructs. For instance:

<?

// Initial values.
$biggest = 1;
$smallest = 10;

// Instead of using a temporary variable...
$temp = $biggest;
$biggest = $smallest;
$smallest = $temp;

// ...Just swap the values.
list($biggest, $smallest) = array($smallest, $biggest);

?>

This works with any number of variables; you're not limited to just two.
Cheers,
Jeronimo
rubein at earthlink dot net
28-Dec-2000 05:15
Note: If you have an array full of arrays, you can't use list() in conjunction to foreach() when traversing said array, e.g.

$someArray = array(
  array(1, "one"),
  array(2, "two"),
  array(3, "three")
);

foreach($somearray as list($num, $text)) { ... }


This, however will work

foreach($somearray as $subarray) {
  list($num, $text) = $subarray;
  ...
}

<ksortnatcasesort>
 Last updated: Tue, 15 Nov 2005