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

If your array has unique array values, then determining the first and last element is trivial:

foreach($array as $element) {
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

As you see, this works if last and first elements are appearing just once in an array. In case they are not, you have to compare the keys (they are unique for sure). This as also the preferred method, if you are concerned about the performance.

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

    end($array);
    if ($key === key($array))
        echo 'LAST ELEMENT!';
}

Source

http://stackoverflow.com/questions/1070244/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop

Leave a comment