How to determine the first and last iteration in a foreach loop?

前端 未结 20 1328
遇见更好的自我
遇见更好的自我 2020-11-22 16:45

The question is simple. I have a foreach loop in my code:

foreach($array as $element) {
    //code
}

In this loop, I want to r

20条回答
  •  日久生厌
    2020-11-22 17:13

    An attempt to find the first would be:

    $first = true; 
    foreach ( $obj as $value )
    {
      if ( $first )
      {
        // do something
        $first = false; //in order not to get into the if statement for the next loops
      }
      else
      {
        // do something else for all loops except the first
      }
    }
    

提交回复
热议问题