如何确定foreach循环中的第一个和最后一个迭代? [英] How to determine the first and last iteration in a foreach loop?

查看:659
本文介绍了如何确定foreach循环中的第一个和最后一个迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单。在我的代码中有一个 foreach 循环:


$ b $ $ $ $ $ $ $ foreach $ array作为$ element){
// code
}

在这个循环中,我想反应不同,当我们在第一次或最后一次迭代。

如何做到这一点?

你可以使用计数器:

  $ i = 0;解决方案


$ len = count($ array);
foreach($ array as $ item){
if($ i == 0){
// first
} else if($ i == $ len - 1) {
// last
}
// ...
$ i ++;
}


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.

How to do this?

解决方案

You could use a counter:

$i = 0;
$len = count($array);
foreach ($array as $item) {
    if ($i == 0) {
        // first
    } else if ($i == $len - 1) {
        // last
    }
    // …
    $i++;
}

这篇关于如何确定foreach循环中的第一个和最后一个迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆