PHP - 使用 foreach 抓取第一个元素 [英] PHP - Grab the first element using a foreach

查看:48
本文介绍了PHP - 使用 foreach 抓取第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道在 foreach 循环中获得第一次迭代的好方法是什么.我想在第一次迭代中做一些不同的事情.

Wondering what would be a good method to get the first iteration on a foreach loop. I want to do something different on the first iteration.

在这些情况下,有条件是我们最好的选择吗?

Is a conditional our best option on these cases?

推荐答案

是的,如果您无法以不同的方式(正常的 for 循环)遍历对象,在这种情况下只需使用条件:

Yes, if you are not able to go through the object in a different way (a normal for loop), just use a conditional in this case:

$first = true;
foreach ( $obj as $value )
{
    if ( $first )
    {
        // do something
        $first = false;
    }
    else
    {
        // do something
    }

    // do something
}

这篇关于PHP - 使用 foreach 抓取第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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