How to find first and last iteration of foreach in PHP

How to find first and last iteration of foreach in PHP

In this article let’s understand how to find first and last iteration of foreach in PHP.

Foreach loop is used to iterate over elements of array and objects. But, it does not have any default function to find first and last element from iteration but by using various other methods we can find them. Let’s explore them.

1. Using counter variable :

We can use a variable and to keep the track of iteration and by incrementing it over the iteration we can find first, last and current iteration. check below :

$myArray = [1, 2, 3, 4, 5];
$length = count($myArray);
$counter = 0;

foreach ($myArray as $item) {
    $counter++;
    if ($counter === 1) {
        echo "First iteration: $item\n";
    } elseif ($counter === $length) {
        echo "Last iteration: $item\n";
    }
}
Output :
First iteration: 1
Last iteration: 5

2. Using key and count :

When using foreach we also have key variable over the loop, so by using direct key variable and count of array elements we can find first and last iteration. See below :

$myArray = [1, 2, 3, 4, 5];

foreach ($myArray as $key => $item) {
    if ($key === 0) {
        echo "First iteration: $item\n";
    }elseif ($key === count($myArray) - 1) {
        echo "Last iteration: $item\n";
    }
}
Output :
First iteration: 1
Last iteration: 5

3. Using ‘array_key_first’ & ‘array_key_last’

These two functions are only available from php version 7.3 so will work only for this. We will use ‘array_key_first’ to identify first key from array and ‘array_key_last’ to identify last key from array.

$myArray = [1, 2, 3, 4, 5];

foreach ($myArray as $key => $item) {
    if ($key === array_key_first($myArray)) {
         echo "First iteration: $item\n";
    }
    if ($key === array_key_last($myArray)) {
        echo "Last iteration: $item\n";
    }
}
Output :
First iteration: 1
Last iteration: 5

So that’s it on how to find first and last iteration of foreach in PHP.

See other articles on PHP here.