【发布时间】:2011-08-20 14:19:11
【问题描述】:
就像迭代一个数组,然后使用索引变量而不是 count() :
foreach($arr as $index => $val){
...
}
echo 'number of items: '.$index+1;
?
【问题讨论】:
就像迭代一个数组,然后使用索引变量而不是 count() :
foreach($arr as $index => $val){
...
}
echo 'number of items: '.$index+1;
?
【问题讨论】:
语言明确表示可以接受。
不过,我不会推荐它,因为在循环之外重用循环特定的值是不寻常的,如果您稍后重构循环并在几行之后忘记依赖关系,您可能会引入错误。实际上,在循环之后显式地unset($index, $val) 来避免此类问题并不是一个坏主意。如果您按引用循环 (foreach ($foo as &$bar)),则尤其如此。
【讨论】:
你可以这样做,虽然我个人不会使用它。
如果您稍后需要更改某些内容,例如跳过一个条目,该怎么办。
foreach($arr as $index => $val){
if ($index > 3) continue;
}
echo 'number of items: '.$index+1; // now this will fail
所以你可以使用它,但我不会这样做
【讨论】:
也许这是一个更好的选择:
foreach($arr as $index => $val){
if ($index > 3) continue;
}
echo 'number of items: '.count($arr);
【讨论】: