Home >Backend Development >PHP Tutorial >list()和each()有关问题

list()和each()有关问题

WBOY
WBOYOriginal
2016-06-13 12:18:13983browse

list()和each()问题

本帖最后由 u014402634 于 2015-04-02 21:06:29 编辑
<br />$fruit = array('a' =>'apple','b'=>'banana','c'=>'cranberry' );<br />reset($fruit);<br />while (list($key,$val)=each($fruit))<br />{<br />	echo "$key=>$val<br>";<br />}<br />//------------------------------------------------------------------------<br /><br /><br />each()不是由4个元素构成么<br />比如第一个是 Array ( [1] => apple [value] => apple [0] => a [key] => a )<br />看手册说list()是从最右边参数开始赋值的  <br />each()4个元素究竟怎么赋值给list两个元素  按理说不是把前两个apple赋值给$key和$val了吗? <br />为啥最后echo能正常输出 对应的 键值对 呢?<br /><br />


------解决思路----------------------
你不看手册的吗?
注: list() 仅能用于数字索引的数组并假定数字索引从 0 开始。

$fruit = array('a' =>'apple');<br />print_r(each($fruit));<br />
Array<br />(<br />    [1] => apple<br />    [value] => apple<br />    [0] => a<br />    [key] => a<br />)<br />
reset($fruit);<br />list($key, $value) = each($fruit);<br />echo "$key => $value";<br />
a => apple
只有数字索引的部分被指派
这样清楚点
$ar = array('a', 'b', 'c' => 'c');<br />list($a, $b, $c) = $ar; //会有 Undefined offset: 2 警告<br />echo "$a $b $c\n";<br />

是按下标递增分配的
$ar = array(1 => 'a', 2 => 'b', 0 => 'c');<br />list($a, $b, $c) = $ar;<br />echo "$a $b $c\n";<br />
c a b
是从右往左分配的
$ar = array('a', 'b', 'c');<br />list($aa[$b][$c], $b, $c) = $ar;<br />print_r($aa);
Array<br />(<br />    [b] => Array<br />        (<br />            [c] => a<br />        )<br /><br />)<br />
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP开发运作环境搭建Next article:PHP惯用内置函数