PHPのお勉強!

PHP TOP

list

(PHP 4, PHP 5, PHP 7, PHP 8)

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

説明

list(mixed $var, mixed ...$vars = ?): array

array() と同様に、 この関数は実際には関数ではなく言語構造です。 list() は、 単一の操作で一連の変数に値を代入するために使われます。 この関数は、文字列を扱うことは出来ませんし、 list() には、空の式を指定できません。

注意:

PHP 7.1.0 より前のバージョンでは、list() は数値添字の配列でのみ動作し、 また、添字は 0 から始まることを想定していました。

パラメータ

var

変数。

vars

残りの変数。

戻り値

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

変更履歴

バージョン 説明
7.3.0 配列へ分割して代入する操作が、リファレンスへの代入をサポートしました。
7.1.0 キーを list() 関数で指定できるようになりました。 これによって、キーが数値でなかったり、連続していなかったりした場合に配列の構造を変えることができるようになります。

例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() の使用法の例

<?php
result
= $pdo->query("SELECT id, name FROM employees");
while (list(
$id, $name) = $result->fetch(PDO::FETCH_NUM)) {
echo
"id: $id, name: $name\n";
}
?>

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

<?php

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

var_dump($a, $b, $c);

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

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

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

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

例5 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() - 配列からシンボルテーブルに変数をインポートする

add a note

User Contributed Notes 24 notes

up
144
carlosv775 at gmail dot com
7 years 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
144
Rhamnia Mohamed
7 years 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
99
grzeniufication
10 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
78
megan at voices dot com
11 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
78
chris at chlab dot ch
12 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
56
grzeniufication
7 years 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
7
nek dot dev at gmail dot com
1 year ago
It can be convenient to specify a default value in case an element is missing in the list. You can use operator + for this:

<?php
$someArray
= ['color' => 'orange'];
[
'color' => $color, 'size' => $size] = $someArray + ['color' => null, 'size' => null];
?>

This will avoid the warning `Undefined array key "size"` you would encounter otherwise.
up
38
pemapmodder1970 at gmail dot com
8 years 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
29
john at jbwalker dot com
11 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
9
diyor024 at gmail dot com
3 years ago
Don't miss simple array pattern matching since php 7

<?php

[$a] = ['hello!'];
var_dump($a); // 'hello!'

$arr = [4 => 50];
[
4 => $fifty] = $arr;
var_dump($fifty); // 50

$multidimensionalArray = [['id' => 15, 'email' => 'diyor024@gmail.com']];
[[
'id' => $id, 'email' => $email]] = $multidimensionalArray;
var_dump($id, $email); // 15 diyor024@gmail.com

?>
up
7
vike2000 at gmail dot com
4 years ago
Setting it like <?php list($var1,$varN) = null ?> does _not_ raise an E_NOTICE (or other error) and afaics effectively equals an https://php.net/function.unset of $var1,$varN.

I note this as contrasting with the fact that PHP triggers an E_NOTICE about "Undefined offset" "if there aren't enough array elements to fill the list()", as attow documented for https://php.net/control-structures.foreach#control-structures.foreach.list and here only noted in https://php.net/function.list#122951 by Mardaneus.

For completeness, a bash(1) (v5.0 or 4.3 on macos10.13) cli test producing the same result for all my PHP-versions (installed via macports.org) follows. It's also tested with php7.3 using bash5.0 on Debian10:
bash --noprofile --norc -c 'for php in php{{53..56},{70..73}};do for literal in "array()" null;do echo -n $php …=$literal:&&$php -n -d error_reporting=E_ALL -r "var_dump(list(\$var)=$literal);";done;done'

# Above produces the same result pairs per version from:
php53 …=array():
Notice: Undefined offset: 0 in Command line code on line 1
array(0) {
}
# ... to:
php73 …=null:NULL
up
48
svennd
11 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
8
mark at manngo dot net
3 years ago
For PHP 7.1 on, the documentation states that integer and string keys can be mixed, but that elements with and without keys cannot. Here is an example, using data from getimagesize() with mixed keys:

<?php
$data
=[
0=> 160,
1 => 120,
2 => 2,
3 => 'width="160" height="120"',
'mime' => 'image/jpeg'
];
list(
0=>$width,1=>$height,2=>$type,3=>$dimensions,'mime'=>$mime)=$data;
?>

Here, the numeric keys also need to be specified, as if the whole array is treated as an associative array.

As noted elsewhere, the list() operator can be written in array format:

<?php
[0=>$width,1=>$height,2=>$type,3=>$dimensions,'mime'=>$mime]=$data;
?>