• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • list()

    (PHP 4, PHP 5, PHP 7)

    把数组中的值赋给一组变量

    说明

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

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

    Note:

    在 PHP 7.1.0 之前的版本,list()仅能用于数字索引的数组,并假定数字索引从 0 开始。

    Warning

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

    如果你用单纯的变量,不用担心这一点。但是如果你用了具有索引的数组,通常你期望得到的结果和在list()中写的一样是从左到右的,但在 PHP 5 里实际上不是,它是以相反顺序赋值的。

    通常而言,不建议依赖于操作的顺序,在未来可能会再次发生修改。

    Warning

    list()执行过程中修改数组(比如使用list($a,$b)=$b)将会产生不可预知的结果。

    参数

    $var1

    一个变量。

    返回值

    返回指定的数组。

    更新日志

    版本说明
    7.1.0现在可以指定list()中的键。这就可以解构非数字键或者无顺序的数组。
    7.0.0赋值操作的顺序发生了变化。
    7.0.0list()表达式不再可以完全为空。
    7.0.0字符串无法再被拆包(unpack)。

    范例

    Example #1list()例子

    <?php
    $info = array('coffee', 'brown', 'caffeine');
    // 列出所有变量
    list($drink, $color, $power) = $info;
    echo "$drink is $color and $power makes it special.\n";
    // 列出他们的其中一个
    list($drink, , $power) = $info;
    echo "$drink has $power.\n";
    // 或者让我们跳到仅第三个
    list( , , $power) = $info;
    echo "I need $power!\n";
    // list() 不能对字符串起作用
    list($bar) = "abcde";
    var_dump($bar); // NULL
    ?>
    

    Example #2list()用法的一个例子

    <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>

    使用嵌套的list()

    <?php
    list($a, list($b, $c)) = array(1, array(2, 3));
    var_dump($a, $b, $c);
    ?>
    
    int(1)
    int(2)
    int(3)
    

    list()中使用数组索引

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

    产生如下输出(注意单元顺序和list()语法中所写的顺序的比较):

    Output of the above example in PHP 7:

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

    Output of the above example in PHP 5:

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

    Example #5list()和索引顺序定义

    list()使用 array 索引的顺序和它何时定义无关。

    <?php
    $foo = array(2 => 'a', 'foo' => 'b', 0 => 'c');
    $foo[1] = 'd';
    list($x, $y, $z) = $foo;
    var_dump($foo, $x, $y, $z);

    得到以下输出(注意比较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"
    

    带键的list()

    从 PHP 7.1.0 开始,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() 从数组中将变量导入到当前的符号表
    Since PHP 7.1, keys can be specified
    exemple : 
    <?php 
    $array = ['locality' => 'Tunis', 'postal_code' => '1110'];
    list('postal_code' => $zipCode, 'locality' => $locality) = $array;
    print $zipCode; // will output 1110
    print $locality; // will output Tunis
     ?>
    
    In PHP 7.1 we can do the following:
    <?php
      [$a, $b, $c] = ['a', 'b', 'c'];
    ?>
    Before, we had to do:
    <?php
      list($a, $b, $c) = ['a', 'b', 'c'];
    ?>
    
    <?php
    /**
     * It seems you can skip listed values.
     * Here's an example to show what I mean.
     *
     * FYI works just as well with PHP 7.1 shorthand list syntax.
     * Tested against PHP 5.6.30, 7.1.5
     */
    $a = [ 1, 2, 3, 4 ];
    // this is quite normal use case for list
    echo "Unpack all values\n";
    list($v1, $v2, $v3, $v4) = $a;
    echo "$v1, $v2, $v3, $v4\n";
    unset($v1, $v2, $v3, $v4);
    // this is what I mean:
    echo "Skip middle\n";
    list($v1, , , $v4) = $a;
    echo "$v1, $v2, $v3, $v4\n";
    unset($v1, $v2, $v3, $v4);
    echo "Skip beginning\n";
    list( , , $v3, $v4) = $a;
    echo "$v1, $v2, $v3, $v4\n";
    unset($v1, $v2, $v3, $v4);
    echo "Skip end\n";
    list($v1, $v2, , ) = $a;
    echo "$v1, $v2, $v3, $v4\n";
    unset($v1, $v2, $v3, $v4);
    echo "Leave middle\n";
    list( , $v2, $v3, ) = $a;
    echo "$v1, $v2, $v3, $v4\n";
    unset($v1, $v2, $v3, $v4);
    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.
    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) ""
    */
    ?>
    
    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"
    ?>
    
    list() can be used with foreach
    <?php
    $array = [[1, 2], [3, 4], [5, 6]];
    foreach($array as list($odd, $even)){
      echo "$odd is odd; $even is even", PHP_EOL;
    }
    ?>
    The output:
    ===
    1 is odd; 2 is even
    3 is odd; 4 is even
    5 is odd; 6 is even
    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
    ?>
    
    Since PHP 7.1 the [] may now be used as an alternative to the existing list() syntax:
    <?php
    [$number, $message] = explode('|', '123|Hello World!');
    ?>
    
    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'
    Unless you specify keys when using list() it expects the array being fed into it to start at 0.
    So having the following code will result in a notice level warning "Undefined offset: 0" and variables not filling as expected
    <?php
    list($c1, $c2, $c3) = array [1 =>'a', 2 => 'b', 3 => 'c'];
    var_dump($c1); // NULL
    var_dump($c2); // string(1) "a"
    var_dump($c3); // string(1) "b"
    ?>
    
    a simple example of use to swap two variables :
    $a = 'hello';
    $b = 'world';
    list($a, $b) = [$b, $a];
    echo $a . ' ' . $b; //display "world hello"
    another example :
    function getPosition($x, $y, $z)
    {
      // ... some operations like $x++...
      return [$x, $y, $z];
    }
    list($x, $y, $z) = getPosition($x ,$y, $z);
    From PHP Version 7.1 you can specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.
    <?php
    $data = [
      ["id" => 1, "name" => 'Tom'],
      ["id" => 2, "name" => 'Fred'],
    ];
    // list() style
    list("id" => $id1, "name" => $name1) = $data[0];
    // [] style
    ["id" => $id1, "name" => $name1] = $data[0];
    // list() style
    foreach ($data as list("id" => $id, "name" => $name)) {
      // logic here with $id and $name
    }
    // [] style
    foreach ($data as ["id" => $id, "name" => $name]) {
      // logic here with $id and $name
    }
    This is something I haven't seen in documentation.
    Since PHP 7.1, you can use short-hand list unpacking using square brackets, just like short-hand array declaration:
    <?php
    $foo = ['a', 'b', 'c'];
    // short-hand array definition
    [$a, $b, $c] = $foo;
    echo $a; // displays "a"
    // it's same like:
    list($x, $y, $z) = $foo;
    echo $x; // displays "a"
    ?>
    
    Since 7.1.0, you can use an array directly without list():
    <?php
    [$test, $test2] = explode(",", "hello, world");
    echo $test . $test2; // hello, world
    ?>
    
    As of PHP 7.3, lists now support array destructuring - see here: https://www.php.net/manual/en/migration73.new-features.php
    If you want use the undefined behaviour as you might expect it e.g. if you want: 
     $b = ['a','b']; list($a, $b) = $b;
    to result in $a=='a' and $b=='b', then you can just cast $b to an array (even although it already is) to create a copy. e.g. 
     $b = ['a','b']; list($a, $b) = (array)$b;
    and get the expected results.
    UNDOCUMENTED BEHAVIOR:
      list($a,$b,$c) = null;
    in fact works like:
      $a = null; $b = null; $c = null;
    ...So correspondingly:
      list($rows[]) = null;
    Will increment count($rows), just as if you had executed $rows[] = null;
    Watch out for this (for example) when retrieving entire tables from a database, e.g.
      while (list($rows[]) = $mysqlresult->fetch_row());
    This will leave an extra 'null' entry as the last element of $rows.

    上篇:ksort()

    下篇:natcasesort()