如何确定foreach循环中的第一次和最后一次迭代? [英] How to determine the first and last iteration in a foreach loop?
本文介绍了如何确定foreach循环中的第一次和最后一次迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题很简单.我的代码中有一个 foreach
循环:
The question is simple. I have a foreach
loop in my code:
foreach($array as $element) {
//code
}
在这个循环中,我想在第一次或最后一次迭代时做出不同的反应.
In this loop, I want to react differently when we are in first or last iteration.
如何做到这一点?
推荐答案
您可以使用计数器:
$i = 0;
$len = count($array);
foreach ($array as $item) {
if ($i == 0) {
// first
} else if ($i == $len - 1) {
// last
}
// …
$i++;
}
这篇关于如何确定foreach循环中的第一次和最后一次迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文