How to Determine the First and Last Iteration in a Foreach loop?

On this page, we are going to figure out how to determine the first and last iteration in a foreach loop with PHP.

Below, you will find three handy methods that will help you to get the answer to this common question in PHP.

Watch a course Learn object oriented PHP

Using a Counter

A handy solution to determining the first and the last iteration in a foreach loop is using a counter. Here is an example:

<?php

$i = 0;
$len = count($array);
foreach ($array as $item) {
  if ($i == 0) {
    // first
  } elseif ($i == $len - 1) {
    // last
  }
  // …
  $i++;
}

?>

Solution For PHP 7.3 and Above

Here is a solution to the issue for the PHP 7.3 and above versions:

<?php

 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

And, here, you can find a universal solution that will work for all PHP versions. You can implement it in the following way:

<?php

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

?>

Describing the foreach Loop in PHP

In PHP, the foreach loop is applied for looping through a block of code for every element inside the array. It is essential to note that the foreach loop only operates on objects and arrays. Once you try to use it on a variable with a different data type, it will issue an error.