list

(PHP 4, PHP 5)

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

Описание

array list ( mixed $varname [, mixed $... ] )

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

Список параметров

varname

Переменная.

Возвращаемые значения

Возвращает присвоенный массив.

Примеры

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

<?php

$info 
= array('кофе''коричневый''кофеин');

// Составить список всех переменных
list($drink$color$power) = $info;
echo 
"$drink - $color, а $power делает его особенным.\n";

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

// Или только третья
list( , , $power) = $info;
echo 
"Мне нужен $power!\n";

// list() не работает со строками
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Пример #2 Пример использования list()

<table>
 <tr>
  <th>Имя работника</th>
  <th>Зарплата</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>

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

<?php

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

var_dump($a$b$c);

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

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

<?php

$info 
= array('кофе''коричневый''кофеин');

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

var_dump($a);

?>

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

array(3) {
  [2]=>
  string(12) "кофеин"
  [1]=>
  string(20) "коричневый"
  [0]=>
  string(8) "кофе"
}

Примечания

Внимание

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

Внимание

Изменение массива во время выполнения функции list() (например, использование list($a, $b) = $b) приводит к непредсказуемому поведению.

Замечание:

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

Смотрите также

  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • array() - Создает массив
  • extract() - Импортирует переменные из массива в текущую таблицу символов

Коментарии

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;
  ...
}
2000-12-28 19:15:37
http://php5.kiev.ua/manual/ru/function.list.html
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
2004-01-28 21:28:57
http://php5.kiev.ua/manual/ru/function.list.html
Автор:
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".
2004-08-14 16:08:54
http://php5.kiev.ua/manual/ru/function.list.html
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.";");
  }
 }
?>
2004-10-21 11:29:56
http://php5.kiev.ua/manual/ru/function.list.html
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 );
2005-02-16 03:29:44
http://php5.kiev.ua/manual/ru/function.list.html
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);
?>
2005-06-01 02:05:38
http://php5.kiev.ua/manual/ru/function.list.html
Автор:
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].";
}
2005-07-25 10:34:33
http://php5.kiev.ua/manual/ru/function.list.html
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
2006-01-02 22:49:25
http://php5.kiev.ua/manual/ru/function.list.html
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
2006-04-06 14:08:24
http://php5.kiev.ua/manual/ru/function.list.html
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?)
2006-05-04 14:29:20
http://php5.kiev.ua/manual/ru/function.list.html
The list construct assigns elements from a numbered array starting from element zero.  It does not assign elements from associative arrays.  So

$arr = array();
$arr[1] = 'x';
list($a, $b) = $arr;
var_dump($a); //outputs NULL because there is no element [0]
var_dump($b); //outputs 'x'

and 

$arr = array('red'=>'stop','green'=>'go');
list($a, $b) = $arr;
var_dump($a); //outputs NULL
var_dump($b); //outputs NULL

If there are not enough elements in the array for the variables in the list the excess variables are assigned NULL.

If there are more elements in the array than variables in the list, the extra array elements are ignored without error.

Also the warning above about order of assignment is confusing until you get used to php arrays.  The order in which array elements are stored is the order in which elements are assigned to the array.  So even in a numbered array if you assign $may_arr[2] before you assign $my_array[0] then element [2] will be in the array before [0].  This becomes apparent when using commands like, push, shift or foreach which work with the stored order of the elements.  So the warning only applies when the variables in the list are themselves array elements which have not already been assigned to their array.
2007-05-08 06:55:13
http://php5.kiev.ua/manual/ru/function.list.html
It's worth noting that, as expected, list() does not have to have as many variables (and/or empty skips) as there are elements in the array. PHP will disregard all elements that there are no variables for. So:

<?php
$Array_Letters 
= array('A''B''C''D''E''F');

list(
$Letter_1$Letter_2) = $Array_Letters;

echo 
$Letter_1 $Letter_2;
?>

Will output: AB

Mick
2007-08-08 15:08:16
http://php5.kiev.ua/manual/ru/function.list.html
PhP manual's NOTE says: list() only works on numerical arrays and assumes the numerical indices start at 0.

I'm finding it do works for associative arrays too,as below:

<?
$tenzin 
= array ("1" => "one""2" => "two","3"=>"three");
while(list(
$keys,$values) = each($tenzin))
echo(
$keys." ".$values."<br>");
?>

gives O/P
1 one 
2 two 
3 three

tsarma
2007-09-18 13:50:54
http://php5.kiev.ua/manual/ru/function.list.html
Автор:
In the code by tenz699 at hotmail dot com, the list() construct is taking values from the result of the each() function, not from the associative array; the example is therefore spurious.

each() returns an array of four elements, indexed in the order 1, 'value', 0, 'key'. As noted in the documentation, the associative keys are ignored, and the numerically-indexed values are assigned in key order.

<?php
$array 
= array('foo'=>'bar');
$t each($array);
print_r($t);
list(
$a,$b,$c,$d) = $t;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>

Output:
Array
(
    [1] => bar
    [value] => bar
    [0] => foo
    [key] => foo
)
string(3) "foo"
string(3) "bar"
NULL
NULL
2007-11-04 14:36:15
http://php5.kiev.ua/manual/ru/function.list.html
With regard to the note written by ergalvan at bitam 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?)

----------

I'm still seeing this behavior in PHP 5.2.5.  Hopefully someone can comment on why it's been changed.
2008-01-19 19:51:03
http://php5.kiev.ua/manual/ru/function.list.html
Another way to do it associative (if your array isn't numeric), is to just use array_values like this:

<?php
$os 
= array();
$os["main"] = "Linux";
$os["distro"] = "Ubuntu";
$os["version"] = "7.10";

list(
$main$distro$version) = array_values($os);
?>
2008-02-06 09:12:56
http://php5.kiev.ua/manual/ru/function.list.html
Автор:
Here's yet another way to make a list()-like construct for associative arrays. This one has the advantage that it doesn't depend on the order of the keys, it only extracts the keys that you specify, and only extracts them into the current scope instead of the global scope (which you can still do, but at least here you have the option).

<?php
    $arr 
= array("foo" => 1"bar" => 2"baz" => 3);
   
$keys = array("baz");

//  $foo = 10;
   
$bar 20;
   
$baz 30;

   
extract(array_intersect_key($arr$keys));

   
var_dump($foo);
   
var_dump($bar);
   
var_dump($baz);
?>

Should print
NULL
int(20)
int(3)

If your version of PHP doesn't have array_intersect_key() yet (below 5.1 I think), it's easy to write a limited feature replacement for this purpose.

<?php
function my_array_intersect_key ($assoc$keys)
{
   
$intersection = array();
    foreach (
$assoc as $key => $val)
        if (
in_array($key$keys))
           
$intersection[$key] = $val;

    return 
$intersection;
}
?>
2008-04-08 22:44:55
http://php5.kiev.ua/manual/ru/function.list.html
A simple way to swap variables (correction of a note of mario dot mueller dot work at gmail dot com below):
<?php
list($var1$var2) = array($var2$var1); // swaps the values of $var1 and $var2
?>
Note that this is not equivalent to:
<?php
$var2 
$var1$var1 $var2// $var1 and $var2 get both the old value of $var1
?>
as one could fear. Indeed, the array is constructed with the values of $var1 and $var2 (and not with the variables $var1 and $var2 themselves) before the assignment is carried out.

Similarly, it is possible to bypass the problem pointed by sasha in the previous note by providing an expression rather than a variable on the right-hand side of the assignment operator:
<?php
$var 
= array ("test" ,"blah");
list (
$a,$var) = $var + array();
echo 
$a // prints "test", not "b"
echo $var // prints "blah"
?>
2009-05-13 06:26:40
http://php5.kiev.ua/manual/ru/function.list.html
Автор:
Quick little function that is similar to list but for objects.

<?php
   
function listObj() {
       
$stack debug_backtrace();
        if (isset(
$stack[0]['args'])) {
           
$i 0;
           
$args $stack[0]['args'];
            foreach (
$args[0] as $key => $value)
               
$args[++$i] = $value;
        }
    }

    class 
obj {public $var "test"; public $vars "test2"; function obj() {}}
   
listObj(new obj, &$var, &$var2);
    echo 
$var$var2;
?>
2010-03-12 11:29:51
http://php5.kiev.ua/manual/ru/function.list.html
Remember, that list starts from index 0. You can skip an index if you just leave the column blank like this:

<?php
list(,$a,$b,$c) = array(1,2,3,4);
?>

You CAN'T (at least not in 5.3.1, what I have tested) set the column to null:

<?php
list(null,$a,$b,$c) = array(1,2,3,4);
?>

This will fail.
2010-03-31 06:37:54
http://php5.kiev.ua/manual/ru/function.list.html
Keep it simple! 
For associative arrays, my replacement for list() is this:
<?php
foreach ($associative_array as $key => $value) { $$key $value; }
?>

Example:
<?php
$petnames 
= array();
$petnames['dog'] = 'Paul';
$petnames['cat'] = 'Lili';

foreach (
$petnames as $name => $value) { $$name $value; }

echo 
'my pets are '.$dog.' and '.$cat;
?>

Will give you:
my pets are Paul and Lili
2011-04-04 19:02:26
http://php5.kiev.ua/manual/ru/function.list.html
If your array is shorter than the number of arguments in list(), you will get an "undefined index" notice.

You can solve it by making sure the array is long enough:

<?php
   $array 
= Array( "one""two" );

   
# This will give a Notice: undefined index [2]:
   
list( $one$two$three ) = $array;

   
# This won't:
   
list( $one$two$three ) = $array + Array( nullnullnull );

   
# If you know count($array) will be at least 1, you could skip the first index:
   
list( $one$two$three ) = $array + Array( => nullnull );

   
# You could of course also use other default values:
   
list( $one$two$three ) = $array + Array( "one""two""three" );
?>
2011-04-06 15:49:40
http://php5.kiev.ua/manual/ru/function.list.html
Note that list(...) isn't limited to scalar variables.
It can even create an associative array:

<?php
$html
=<<<EOT
<table>
<tr class="row-odd">
<td><span class="username">Foo</span></td>
<td><span class="userid">30185</span></td>
</tr><tr class="row-even">
<td><span class="username">Bar</span></td>
<td><span class="userid">3093</span></td>
</tr>
</table>
EOT;

interface 
RegExps
{
    const 
PROFILE_CONTENT='/<tr[^>]*>.*?<span class="username">(.*?)<\/span>[
        ]?.*?<span class="userid">(.*?)<\/span>.*?<\/tr>/msi'
;
}

preg_match_all(RegExps::PROFILE_CONTENT,$html$matches,PREG_SET_ORDER);
$profiles=array();
foreach(
$matches as $match)
{
   
$profile=array();
    list(,
$profile['username'],$profile['userid'])=$match;
   
//$profile=array_reverse($profile);
   
$profiles[]=$profile;
}
echo 
'<pre>'.print_r($profiles,true).'</pre>';
?>

Just be careful, as the manual warns us, regarding the right-most parameter being handled first.
If this becomes a problem, I'd suggest using array_reverse as shown in my code.
2011-05-08 18:37:36
http://php5.kiev.ua/manual/ru/function.list.html
Although the warning claims of undefined behaviour, it's reasonably straightforward what happens.

<?php
    $a 
= array(123);
    list(
$a$b$c) = $a;
   
var_dump($a$b$c);
   
// int(1)
    // int(2)
    // int(3)
?>

Since list() works from right to left on the target variables, $a is replaced last, thus keeping the remaining array element values around long enough to populate $b and $c.

<?php
    $a 
= array(123);
    list(
$c$b$a) = $a;
   
var_dump($a$b$c);
   
// int(3)
    // NULL
    // NULL
?>

$a is populated first (remember, right to left) with the value 3 from itself. Since $a is no longer an array, list() is forced to substitute NULL values for $b and $c.

This appears to be perfectly sensible, though there may be edge cases and other strange behaviour I'm unaware of.
2012-01-14 19:43:49
http://php5.kiev.ua/manual/ru/function.list.html

    Поддержать сайт на родительском проекте КГБ