Fonction list

La fonction list extrait les éléments d'un tableau dans des variables.

Syntaxe

phplist(mixed $var, mixed ...$vars): array

Exemple

Extrayons les éléments d'un tableau dans des variables :

php<?php
  $arr = [1, 2, 3, 4, 5];
  list($a, $b, $c, $d, $e) = $arr;
?>

En conséquence, nous aurons accès à la variable $a, la variable $b, la variable, la variable $c, la variable $d, la variable $e :

php<?php
  echo $a; // affichera 1
  echo $b; // affichera 2
  echo $c; // affichera 3
  echo $d; // affichera 4
  echo $e; // affichera 5
?>

Exemple

Si vous devez commencer non pas par le premier élément du tableau - vous pouvez mettre une virgule :

php<?php
  $arr = [1, 2, 3, 4, 5];
  list(, $b, $c, $d, $e) = $arr;
?>

En conséquence, nous aurons accès à la variable $b, la variable $c, la variable $d et la variable $e :

php<?php
  echo $b; // affichera 2
  echo $c; // affichera 3
  echo $d; // affichera 4
  echo $e; // affichera 5
?>

Exemple

Enregistrons uniquement le troisième élément du tableau dans une variable :

php<?php
  $arr = [1, 2, 3, 4, 5];
  list(, , $c) = $arr;
?>

En conséquence, nous aurons accès à la variable $c :

php<?php
  echo $c; // affichera 3
?>

Voir aussi

  • la fonction extract,
    qui divise un tableau en variables