English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP list() Function Usage and Example

PHP Array Function Manual

The list() function assigns the values of an array to a group of variables

Syntax

list ( $var1, $var2, $var3.. )

定义和用法

 像 array() 一样,这不是真正的函数,而是语言结构。 list() 可以在单次操作内就为一组变量赋值。

注意:PHP 5 里,list() 从最右边的参数开始赋值; PHP 7 里,list() 从最左边的参数开始赋值。

参数

序号参数及说明
1

var1(必需)

要为其赋值的第一个变量

2

var2(可选)

要为其赋值的第二个变量

3

var3(可选)

要为其赋值的第三个变量

返回值

这不会返回任何内容。

Online Example

<?php
   $fruit = array("mango","apple","banana");
   
   list($a, $b, $c) = $fruit;
   echo "我有几个水果, $a, $b 和 $c.";
?>
测试看看‹/›

Output Result:

我有几个水果, mango, apple 和 banana

Online Example

在 list() 中使用数组索引

<?php
$info = array('coffee', 'brown', 'caffeine');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);
?>
Test to see ‹/›

Output Result:

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

Online Example

List() with keys, from PHP 7.1. Starting from PHP 5.0, list() can include explicit keys, which can be assigned to any expression. You can mix numeric and string keys. However, you cannot mix keys and no keys, and they cannot be mixed.

<?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";
?>
Test to see ‹/›

Output Result:

id: 1, name: Tom
id: 2, name: Fred
2, 4

   PHP Array Function Manual