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

前端 未结 20 1171
遇见更好的自我
遇见更好的自我 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:12

    I came across this thread when I have the same problem. I only need to get the first element then I re-analyze my code until this came up to my mind.

    $firstElement = true;
    
    foreach ($reportData->result() as $row) 
    {
           if($firstElement) { echo "first element"; $firstElement=false; }
           // Other lines of codes here
    }
    

    The above codes are great and complete but if you only need just the first element then you may try this code.

提交回复
热议问题