Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : list

list

Assign variables as if they were an array (PHP 4, PHP 5)
void list ( mixed varname, mixed ... )

Example 312. 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 313. 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 314. 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"
}

Related Examples ( Source code ) » list
















Code Examples / Notes » list

ergalvan

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?)


jennevdmeer

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.";");
 }
}
?>


mortoray

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 );


hw

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".


tobylewis

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.


tenz699

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."
");
?>
gives O/P
1 one  
2 two
3 three
tsarma


webmaster

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);
?>


rubein

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;
 ...
}


nearsighted

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].";
}


mick

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


hayley watson

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


jeronimo

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


dolan

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

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


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker