PHP - 使用 foreach 抓取第一个元素

2021-12-26 00:00:00 iteration foreach php

想知道在 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
}

相关文章