如何在不使用“计数器”的情况下找出 PHP 中 foreach 构造循环的次数?多变的?
如果我有一个 foreach
构造,如下所示:
foreach ($items as $item) {
echo $item . "<br />";
}
我知道我可以使用计数器变量来跟踪构造循环的次数,如下所示:
$counter = 0;
$foreach ($items as $item) {
echo $item.' is item #'.$counter. "<br />";
$counter++;
}
但是是否可以执行上述操作不使用“计数器”变量? 也就是说,是否可以知道 foreach 循环内的迭代计数,而无需“计数器”变量?
注意:我完全同意在循环中使用计数器,但我只是好奇是否有直接内置到 PHP 中的规定...这就像很棒的 foreach
构造一样简化了某些操作,这些操作在使用 for
结构执行相同操作时会比较笨重。
If I have a foreach
construct, like this one:
foreach ($items as $item) {
echo $item . "<br />";
}
I know I can keep track of how many times the construct loops by using a counter variable, like this:
$counter = 0;
$foreach ($items as $item) {
echo $item.' is item #'.$counter. "<br />";
$counter++;
}
But is it possible to do the above without using a "counter" variable?
That is, is it possible to know the iteration count within the foreach
loop, without needing a "counter" variable?
Note: I'm totally okay with using counters in my loops, but I'm just curious to see if there is a provision for this built directly into PHP... It's like the awesome foreach
construct that simplified certain operations which are clunkier when doing the same thing using a for
construct.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这是不可能的,除非您的
$items
是一个具有以 0 键开头的连续索引(键)的数组。如果它有连续索引,那么:
但正如其他人所说,使用计数器变量没有任何问题。
No it's not possible unless your
$items
is an array having contiguous indexes (keys) starting with the 0 key.If it have contiguous indexes do:
But as others have stated, there is nothing wrong using a counter variable.
没有更简单的方法了——这就是计数变量的用途。
我假设您想知道循环期间的当前计数。如果您只是需要知道它,请按照其他人的建议使用
count($items)
。There's no easier way - that's kinda what count variables are for.
I'm assuming that you want to know the current count during the loop. If you just need to know it after, use
count($items)
as others have suggested.您可以通过执行“但是”来判断它将循环或应该循环多少次,
但是只有当您的代码不以任何方式跳过迭代时,这才有效。
You could tell how many time it WILL loop or SHOULD have looped by doing a
However that will only work if your code does not skip an iteration in any way.
foreach 循环 N 次,其中 N 就是数组的大小。所以你可以使用
count($items)
来知道。编辑
当然,正如 Bulk 所注意到的,您的循环不应中断(或者可能继续,但我会将
continue
算作循环,尽管更短......)foreach loops N times, where N is just the size of the array. So you can use
count($items)
to know it.EDIT
Of course, as noticed by Bulk, your loop should not break (or maybe continue, but I would count a
continue
as a loop, though shorter...)