Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Target the Last Item in a PHP foreach Loop

David Egan

To target the last item in a PHP foreach loop without using a counter, check for count( $array ) -1 within the loop.

This simple example assigns appropriate classes to the rendered elements:


foreach ($array as $key => $value) {

  $class = ( $key !== count( $array ) -1 ) ? " class='not-last'" : " class='last'";

  echo "<div{$class}>";
  echo "$value['the_title']";
  echo "</div>";


comments powered by Disqus