PHP - Grab the first element using a foreach

后端 未结 8 942
面向向阳花
面向向阳花 2020-12-14 07:11

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 b

8条回答
  •  醉梦人生
    2020-12-14 07:56

    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
    }
    

提交回复
热议问题