downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

natcasesort> <ksort
Last updated: Fri, 24 Jul 2009

view this page in

list

(PHP 4, PHP 5)

list배열처럼 변수에 할당

설명

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

array()처럼, 이 함수는 실제 함수가 아니고 언어 구조이다. list()는 한번의 조작으로 배열 목록을 지정하기 위해 사용된다.

인수

varname

변수.

반환값

값을 반환하지 않습니다.

예제

Example #1 list() 예제

<?php

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

// 모든 변수를 목록화한다
list($drink$color$power) = $info;
echo 
"$drink is $color and $power makes it special.\n";

// 그들중 일부를 목록화한다
list($drink, , $power) = $info;
echo 
"$drink has $power.\n";

// 또는 세번째 값으로만 건너띈다
list( , , $power) = $info;
echo 
"I need $power!\n";

// list()는 문자열에는 작동하지 않습니다
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Example #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>\n" .
          
"  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          
"  <td>$salary</td>\n" .
          
" </tr>\n";
}

?>

</table>

Example #3 중첩 list() 사용하기

<?php

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

var_dump($a$b$c);

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

Example #4 배열 인덱스로 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"
}

주의

Warning

list()는 가장 우측 인수에서 시작하는 값들을 지정한다. 일반적인 변수들을 사용하면, 이 동작에 대해서 신경 쓸 필요가 없다. 그러나 인덱스를 갖는 배열에서 사용한다면 왼쪽에서 오른쪽으로 list()에서 쓰여진것과 같이 배열안의 인덱스 순서로 되는것이라고 보통 기대할수 있으나, 그렇지 않다. 역순으로 지정이 된다.

Note: list()는 숫자 배열에서만 작동하고 0부터 시작하는 숫자 인덱스로 가정한다.

참고

  • each() - 배열에서 현재 키와 값 쌍을 반환하고 배열 커서를 전진
  • array() - 배열 생성
  • extract() - 배열에서 현재 심볼 테이블로 변수를 입력



natcasesort> <ksort
Last updated: Fri, 24 Jul 2009
 
add a note add a note User Contributed Notes
list
claude dot pache at gmail dot com
13-May-2009 10:26
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"
?>
sasha
29-Apr-2009 05:08
Note that list assigns values from right to left and it does so as soon as it reached argument.

$var = array ("test" ,"blah") ;
list ($a,$var) = $var;
echo $a ; // prints "b"
echo $var ; // prints "blah"

In this case $var has been assigned new value "blah" before value was assigned to $a.

$a was assigned value "b" (I assume string "blah" was converted to an array and $a was assigned first element of that array).
mario dot mueller dot work at gmail dot com
12-Feb-2009 02:08
Some simple method to exchange values with two variables:

<?php
$var1
= 'John';
$var2 = 'Doe';

list(
$var2,$var1) = list($var1,$var2);
?>
tristan in oregon
09-Apr-2008 02:44
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;
}
?>
kevin at vanzonneveld dot net
06-Feb-2008 03:12
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);
?>
danieljames3 at g mail
20-Jan-2008 01:51
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.
Hayley Watson
04-Nov-2007 08:36
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
tenz699 at hotmail dot com
18-Sep-2007 05:50
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
mick at wireframe dot com
08-Aug-2007 07:08
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
tobylewis at logogriph dot com
08-May-2007 10:55
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.
ergalvan at bitam dot com
04-May-2006 06: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 06: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
03-Jan-2006 04: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 02: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
01-Jun-2005 06: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);
?>
mortoray at ecircle-ag dot com
16-Feb-2005 09: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 03: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 08: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
29-Jan-2004 03: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
29-Dec-2000 01: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;
  ...
}

natcasesort> <ksort
Last updated: Fri, 24 Jul 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites