list
list
Assign variables as if they were an array
array **list** mixed $var mixed $vars
Like , this is not really a function,
but a language construct. is used to
assign a list of variables in one operation.
Only arrays and objects that implement can be unpacked.
expressions can not be completely empty.
array``listArrayAccesslist
Opmerking: > Before PHP 7.1.0, only worked on numerical arrays and assumes the numerical indices start at 0.
list
As of PHP 7.1.0, can also contain explicit keys, allowing for the
destructuring of arrays with non-integer or non-sequential keys. For more details on
array destructuring, see the .
listarray destructuring section
Opmerking: > Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an -level error message (-level prior to PHP 8.0.0) will be issued, and the result will be null.
E_WARNING``E_NOTICEAttempting to unpack a scalar assigns null to all variables. Attempting to unpack an object that does not implement ArrayAccess is a fatal error.
varA variable.
varsFurther variables.
Returns the assigned array.
Voorbeeld: 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
?>
**Voorbeeld: An example use of **
<?php
$result = $pdo->query("SELECT id, name FROM employees");
while (list($id, $name) = $result->fetch(PDO::FETCH_NUM)) {
echo "id: $id, name: $name\n";
}
?>
**Voorbeeld: Using nested **
<?php
list($a, list($b, $c)) = array(1, array(2, 3));
var_dump($a, $b, $c);
?>
int(1)
int(2)
int(3)
The order in which the indices of the array to be consumed by
are defined is irrelevant.
list
Voorbeeld: and order of index definitions
<?php
$foo = array(2 => 'a', 'foo' => 'b', 0 => 'c');
$foo[1] = 'd';
list($x, $y, $z) = $foo;
var_dump($foo, $x, $y, $z);
Gives the following output (note the order of the elements compared in
which order they were written in the syntax):
`list`
array(4) {
[2]=>
string(1) "a"
["foo"]=>
string(1) "b"
[0]=>
string(1) "c"
[1]=>
string(1) "d"
}
string(1) "c"
string(1) "d"
string(1) "a"
Voorbeeld: with keys
As of PHP 7.1.0 can now also contain
explicit keys, which can be given as arbitrary expressions.
Mixing of integer and string keys is allowed; however, elements
with and without keys cannot be mixed.
`list`
<?php
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as ["id" => $id, "name" => $name]) {
echo "id: $id, name: $name\n";
}
echo PHP_EOL;
list(1 => $second, 3 => $fourth) = [1, 2, 3, 4];
echo "$second, $fourth\n";
id: 1, name: Tom
id: 2, name: Fred
2, 4
each``array``extract