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
(PHP 4, PHP 5)
list — انتصاب متغیرها به عنوان آرایه
Description
مانند array() تابع واقعی نیست اما ساختار زبانی است. list() برای انتصاب فهرستی از عملوندها استفاده میشود.
Parameters
- varname
-
متغیر.
Return Values
بازگرداندن آرایه انتصاب داده شده.
Examples
Example #1 مثالهای list()
<?php
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>
Example #2 مثال استفاده list()
<table>
<tr>
<th>Employee name</th>
<th>Salary</th>
</tr>
<?php
$result = mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
echo " <tr>\n" .
" <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
" <td>$salary</td>\n" .
" </tr>\n";
}
?>
</table>
Example #3 استفاده از list() داخل یکدیگر
<?php
list($a, list($b, $c)) = array(1, array(2, 3));
var_dump($a, $b, $c);
?>
int(1) int(2) int(3)
Example #4 استفاده از list() به همراه اندیس آرایهّای
<?php
$info = array('coffee', 'brown', 'caffeine');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);
?>
تولید خروجی زیر (ترتیب همان ترتیب در دستور list() است):
array(3) {
[2]=>
string(8) "caffeine"
[1]=>
string(5) "brown"
[0]=>
string(6) "coffee"
}
Notes
list() مقادیر را با شروع از سمت راست ترین پارامتر انجام میدهد. اگر از متغیرهای ساده استفاده میکنید نیاز به نگرانی در این باره ندارید. اما اگر از آرایهها اندیسدار استفاده میکند همان ترتیب اندیسها را انتظار داشته باشید که list() از چپ به راست نوشتید; که این طور نیست و برعکس آن است.
Note:
list() تنها بر آرایههای عددی کار میکند و فرض بر این است که اندیس از 0 شروع میشود.
Note: list cannot assign array cast of object to variables straight away. first you need to convert the object to numeric indexed array.
ex:
list($a, $b, $d) = (array) $abc; // $abc is an object; this will not assign.
list($a, $b, $c) = array_values((array) $abc); // This will work.
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
?>
