Mestika
10/29/2015 - 8:48 AM

PHP: Determine the first and last iteration in a foreach loop?

PHP: Determine the first and last iteration in a foreach loop?

<?php
// @ http://stackoverflow.com/a/8780881/188082

// CACHED
reset($array);
$first = key($array);

end($array);
$last = key($array);

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

?>