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

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

    A more simplified version of the above and presuming you're not using custom indexes...

    $len = count($array);
    foreach ($array as $index => $item) {
        if ($index == 0) {
            // first
        } else if ($index == $len - 1) {
            // last
        }
    }
    

    Version 2 - Because I have come to loathe using the else unless necessary.

    $len = count($array);
    foreach ($array as $index => $item) {
        if ($index == 0) {
            // first
            // do something
            continue;
        }
    
        if ($index == $len - 1) {
            // last
            // do something
            continue;
        }
    }
    

提交回复
热议问题