PHP 7.2.0 Beta 1 Released

list

(PHP 4, PHP 5, PHP 7)

list配列と同様の形式で、複数の変数への代入を行う

説明

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

array() と同様に、 この関数は実際には関数ではなく言語構造です。 list() は、 単一の操作で一連の変数に値を代入するために使われます。

注意:

list() は数値添字の配列でのみ動作します。 また、添字は 0 から始まることを想定しています。

警告

PHP 5 では、list()は、最も右のパラメータから値を代入します。 PHP 7 では、list()は、最も左のパラメータから値を代入します。

プレーンな変数を使用している場合には、このことを気にする必要はありません。 しかし、添字配列を使用している場合には、配列の添字の順番が list() に書いたものと同じく左から右となることを通常は期待しますが、 PHP 5 ではそうはなりません。この配列の添字は逆の順番となります。

一般論として、特定の操作順に依存することは避けたほうがいいでしょう。 将来的に、その順番が変更される可能性があるからです。

警告

list() を実行して配列を変更 (list($a, $b) = $b など) した場合の挙動は未定義です。

パラメータ

var1

変数。

返り値

代入した配列を返します。

例1 list() の例

<?php

$info 
= array('コーヒー''茶色''カフェイン');

// すべての変数の取得
list($drink$color$power) = $info;
echo 
"$drink の色は $color で、$power が含まれています。\n";

// 一部の変数の取得
list($drink, , $power) = $info;
echo 
"$drink には $power が含まれています。\n";

// 三番目のみの取得
list( , , $power) = $info;
echo 
"$power 欲しい!\n";

// list() は文字列では動作しません
list($bar) = "abcde";
var_dump($bar); // NULL
?>

例2 list() の使用法の例

<table>
 <tr>
  <th>社員氏名</th>
  <th>給与</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>

例3 ネストした list() の使用法

<?php

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

var_dump($a$b$c);

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

例4 配列の添字を使用した list() の例

<?php

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

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

var_dump($a);

?>

次のような出力になります(list() の文法に書かれた 順番と、要素の順番の違いに注意):

上の例の PHP 7 での出力は、このようになります。

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

上の例の PHP 5 での出力は、このようになります。

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

例5 list() と添字の定義順

list() が配列の要素をどの順に処理するかは、配列の添字とは無関係です。

<?php
$foo 
= array(=> 'a''foo' => 'b'=> '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"

参考

  • each() - 配列から現在のキーと値のペアを返して、カーソルを進める
  • array() - 配列を生成する
  • extract() - 配列からシンボルテーブルに変数をインポートする

add a note add a note

User Contributed Notes 15 notes

up
63
chris at chlab dot ch
4 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
15
grzeniufication
1 month ago
<?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);
up
9
Rhamnia Mohamed
2 months ago
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
?>
up
47
megan at voices dot com
3 years 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
11
carlosv775 at gmail dot com
6 months ago
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'];
?>
up
33
grzeniufication
2 years 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
21
pemapmodder1970 at gmail dot com
1 year ago
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
up
38
svennd
4 years 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
13
john at jbwalker dot com
3 years 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
5
Dean
1 year ago
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.
up
0
anthony dot ossent at live dot fr
9 months ago
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);
up
0
Colin Guthrie
2 years ago
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.
up
-1
vickyssj7 at gmail dot com
2 years 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
-11
mogwai512
2 years ago
I see many people offer solutions about the flipped order of the list construct. All you have to do is this:

<?php

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

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

var_dump($a);

?>

. . . and your info will be in the correct order. You can also just assign a new var to the list and it will still work:

<?php

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

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

var_dump($b);

?>
up
-16
Achilles at thegreatwarrior dot com
4 years 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;
To Top