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

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

    If you prefer a solution that does not require the initialization of the counter outside the loop, I propose comparing the current iteration key against the function that tells you the last / first key of the array.

    This becomes somewhat more efficient (and more readable) with the upcoming PHP 7.3.

    Solution for PHP 7.3 and up:

    foreach($array as $key => $element) {
        if ($key === array_key_first($array))
            echo 'FIRST ELEMENT!';
    
        if ($key === array_key_last($array))
            echo 'LAST ELEMENT!';
    }
    

    Solution for all PHP versions:

    foreach($array as $key => $element) {
        reset($array);
        if ($key === key($array))
            echo 'FIRST ELEMENT!';
    
        end($array);
        if ($key === key($array))
            echo 'LAST ELEMENT!';
    }
    

提交回复
热议问题