Dev Notes

Software Development Resources by David Egan.

Target the Last Item in a PHP foreach Loop


PHP
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:

<?php

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