PHP 5.4.36 Released

list

(PHP 4, PHP 5)

listAssigne des variables comme si elles étaient un tableau

Description

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

Tout comme array(), list() n'est pas une véritable fonction, mais un élément de langage, qui permet de rassembler les variables varname, ... sous forme de tableau, pour les assigner en une seule ligne.

Liste de paramètres

var1

Une variable.

Valeurs de retour

Retourne le tableau assigné.

Exemples

Exemple #1 Exemple avec list()

<?php

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

// Liste toutes les variables
list($drink$color$power) = $info;
echo 
"$drink is $color and $power makes it special.\n";

// Liste certaines variables
list($drink, , $power) = $info;
echo 
"$drink has $power.\n";

// Ou bien, n'utilisons que le troisième
list( , , $power) = $info;
echo 
"I need $power!\n";

// list() ne fonctionne pas avec les chaînes de caractères
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Exemple #2 Exemple d'utilisation de list()

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

<?php
$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>

Exemple #3 Utilisation d'un sous-list()

<?php

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

var_dump($a$b$c);

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

Exemple #4 Utilisation de list() en tenant compte de l'ordre

<?php

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

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

var_dump($a);

?>

Cet exemple donne le résultat suivant (notez l'ordre d'affichage des éléments, en comparaison avec l'ordre dans lequel ils ont été écrits dans la syntaxe de list()) :

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

Notes

Avertissement

list() assigne les valeurs en commençant par la valeur la plus à droite. Si vous utilisez ces variables, ce ne sera pas un problème. Mais si vous utilisez des tableaux, vous serez surpris de voir que list() les affecte de droite à gauche.

Avertissement

La modification du tableau lors de l'exécution de la fonction list() (i.e. en utilisant la syntaxe list($a, $b) = $b) conduit à un comportement non-défini.

Note:

list() fonctionne uniquement avec des tableaux à indexation numérique, et suppose que l'indexation commence à 0.

Voir aussi

  • each() - Retourne chaque paire clé/valeur d'un tableau
  • array() - Crée un tableau
  • extract() - Importe les variables dans la table des symboles

add a note add a note

User Contributed Notes 12 notes

up
35
chris at chlab dot ch
2 years ago
The example states the following:
<?php
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar);
// output: NULL
?>

If the string is in a variable however, it seems using list() will treat the string as an array:
<?php
$string
= "abcde";
list(
$foo) = $string;
var_dump($foo);
// output: string(1) "a"
?>
up
21
svennd
1 year ago
The list() definition won't throw an error if your array is longer then defined list.
<?php

list($a, $b, $c) = array("a", "b", "c", "d");

var_dump($a); // a
var_dump($b); // b
var_dump($c); // c
?>
up
3
grzeniufication
2 months ago
The example showing that:

$info = array('kawa', 'brązowa', 'kofeina');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);

outputs:
array(3) {
[2]=>
string(8) "kofeina"
[1]=>
string(5) "brązowa"
[0]=>
string(6) "kawa"
}

One thing to note here is that if you define the array earlier, e.g.:
$a = [0, 0, 0];

the indexes will be kept in the correct order:

array(3) {
  [0]=>
  string(4) "kawa"
  [1]=>
  string(8) "brązowa"
  [2]=>
  string(7) "kofeina"
}

Thought that it was worth mentioning.
up
14
megan at voices dot com
1 year ago
As noted, list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:

<?php
$parameter
= 'name';
list(
$a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>

However, you will have to array_merge with an array long enough to ensure there are enough elements (if $parameter is empty, the code above would still error).

An alternate approach would be to use array_pad on the array to ensure its length (if all the defaults you need to add are the same).

<?php
    $parameter
= 'bob-12345';
    list(
$name, $id, $fav_color, $age ) = array_pad( explode( '-', $parameter ), 4, '' );
   
var_dump($name, $id, $fav_color, $age);
/* outputs
string(3) "bob"
string(5) "12345"
string(0) ""
string(0) ""
*/
?>
up
3
john at jbwalker dot com
1 year ago
The list construct seems to look for a sequential list of indexes rather taking elements in sequence. What that obscure statement means is that if you unset an element, list will not simply jump to the next element and assign that to the variable but will treat the missing element as a null or empty variable:

    $test = array("a","b","c","d");
    unset($test[1]);
    list($a,$b,$c)=$test;
    print "\$a='$a' \$b='$b' \$c='$c'<BR>";

results in:
$a='a' $b='' $c='c'

not:
$a='a' $b='c' $c='d'
up
-1
vickyssj7 at gmail dot com
3 months ago
if we assign array's each value individual key('numeric only'), and use the array indices in list(),, then it output the reverse order of array keys--
BUT THE HIGHER KEY VALUE ("2" in this e.g below) WILL GET THE FIRST PLACE IN THE ARRAY IN RETURN, MEANS IT PUSHES THE VALUE WITH HIGHER KEY IN PLACE OF FIRST KEY VALUE, so it also gives higher key value the first priority while reversing the order of the keys and replacing the lower key value with the higher key value.

        $value = array( 0 => 'low', 2 => 'medium', 1 => 'higher');
        list($a[2], $a[1], $a[0]) = $value;
    var_dump($a);

//Outputs:---
array(3) {
            [0] => string(6) "medium"
            [1]  => string(6) "higher"
            [2]  => string(3) "low"
}
up
-5
edam
10 months ago
This doesn't work on associative array.  For example:

    list( $a, $b, $c ) = array( 'a' => 'a', 'b' => 'b', 'c' => 'c' );
    PHP Notice:  Undefined offset: 2 in Command line code on line 1
    PHP Notice:  Undefined offset: 1 in Command line code on line 1
    PHP Notice:  Undefined offset: 0 in Command line code on line 1
up
-4
srikanth at networthindia dot com
1 year ago
Note: list cannot assign array cast of object to variables straight away. first you need to convert the object to numeric indexed array.

ex:
list($a, $b, $d) = (array) $abc; // $abc is an object; this will not assign.
list($a, $b, $c) = array_values((array) $abc); // This will work.
up
-4
Arne
1 year ago
list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:

<?php
$parameter
= 'name';
list(
$a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>
up
-8
Matt
1 year ago
You can't type check within the list() parameters:

list ( array $var1, $var2 ) = array ( array('one','two'), 'three');

generates a parse error, unexpected 'array'.
up
-5
Achilles at thegreatwarrior dot com
1 year ago
Second, when you’re using the list() function, you must acknowledge each array element. You could not do this
list($weekday, $month) = $date;

But you can use empty values to ignore elements:
list ($weekday, , $month) = $date;
up
-10
Thanos K.
9 months ago
Also it seems that it doesn't work as expected with arrays with non numeric keys:

list($k, $l, $m) = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3');

Gives empty variables..
To Top