Menu Home

list

osbo.com | PHP | Functions | list

Assign variables as if they were an array

Syntax

list ( mixed $var1 [, mixed $... ] ) : array

Parameters

var1

A variable.

Return

Returns the assigned array.

Examples

1

<?

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

// list all variables
list($var1, $var2, $var3) = $array;
echo "$var1 is $var2 and $var3 makes it special.\n";

// list some variables
list($var1, , $var3) = $array;
echo "$var1 has $var3.\n";

// list last variable
list( , , $var3) = $array;
echo "I need $var3!\n";

// list() does not work with strings
$string = "abcde";
list($var1) = $string;
var_dump($var1);

?>
coffee is brown and caffeine makes it special.
coffee has caffeine.
I need caffeine!
NULL

2

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

<?

$result = $pdo->query("SELECT id, name, salary FROM employees");
while (list($id, $name, $salary) = $result->fetch(PDO::FETCH_NUM)) {
    echo "  <tr>\n"
        ."    <td><a href=\"info.php?id=$id\">$name</a></td>\n"
        ."    <td>$salary</td>\n"
        ."  </tr>\n";
}

?>

</table>

			
			
		

3

<?

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

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

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

4

<?

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

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

print_r($a);

?>
Array
(
    [2] => coffee
    [1] => brown
    [0] => caffeine
)

5

<?

$array = array(2 => 'a', 'some' => 'b', 0 => 'c');
$array[1] = 'd';

list($x, $y, $z) = $array;

var_dump($array, $x, $y, $z);

?>
array(4) {
  [2]=>
  string(1) "a"
  ["some"]=>
  string(1) "b"
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
}
string(1) "c"
string(1) "d"
string(1) "a"

6

<?

list(1 => $second, 3 => $fourth) = array(1, 2, 3, 4);

echo "$second, $fourth\n";

?>
2, 4

PHP