Open In App

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

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In PHP, determining the first and last iteration in a foreach loop helps identify specific elements in a looped collection. The first iteration can be identified by a counter starting at zero, while the last iteration can be detected by comparing keys or counts.

There are many ways to solve this problem which are listed below:

Method 1: Naive method

It is the naive method inside for each loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.

Example: In this example we identifies the first and last iteration in a foreach loop using a counter. The first element is detected when the counter is 0, and the last when it reaches the array length minus one.

php
<?php

// PHP program to get first and
// last iteration

// Declare an array and initialize it
$myarray = array( 1, 2, 3, 4, 5, 6 );

// Declare a counter variable and
// initialize it with 0
$counter = 0;

// Loop starts from here
foreach ($myarray as $item) {
    
    // Check condition if count is 0 then 
    // it is the first iteration
    if( $counter == 0 ) {
        
        // Print the array content
        print( $item );
        print(": First iteration \n");
    }
    
    // Check condition if count is length -1 
    // then it is last iteration
    if( $counter == count( $myarray ) - 1) {
        
        // Print the array content
        print( $item );
        print(": Last iteration");
    }
        
    $counter = $counter + 1;
}

?>

Output
1: First iteration 
6: Last iteration

Method 2: Using reset and end function

Here we are Using reset and end function to find first and last iteration. The reset() function is an inbuilt function in PHP which takes array name as argument and return first element of array. The end() function is an inbuilt function in PHP which takes array name as argument and returns its last element.

Example: This PHP script checks for the first and last elements in an array during a foreach loop. It uses flags ($firstProcessed and $lastProcessed) to ensure that duplicate first and last values are ignored.

php
<?php

// PHP program to get first and last iteration
// and ignore duplicates of the first and last values.

$myarray = array( 1, 2, 3, 4, 5, 6 );

// Flags to track first and last iterations
$firstProcessed = false;
$lastProcessed = false;

foreach ( $myarray as $item ) {

    // Check first element
    if ( !$firstProcessed && $item === reset( $myarray ) ) {
        print( $item . ": First iteration \n");
        $firstProcessed = true;
    }

    // Check last element
    else if( !$lastProcessed && $item === end( $myarray ) ) {
        print( $item . ": Last iteration \n");
        $lastProcessed = true;
    }
}
?>

Output
1: First iteration 
6: Last iteration 

Method 3: Using reset() function

The reset() function is used to find the first iteration in foreach loop. When there is no next element is available in an array then it will be the last iteration and it is calculated by next() function.

Example: This PHP script identifies and prints the first and last elements in an array while ensuring duplicates are ignored. It uses flags ($firstDisplayed, $lastDisplayed) to prevent multiple outputs of the first and last iterations.

php
<?php

// PHP program to get first and last iteration with duplicates ignored

$myarray = array( 1, 2, 3, 4, 5, 6 );

// Get first and last elements
$first = reset($myarray);
$last = end($myarray);

// Flags to track first and last display
$firstDisplayed = false;
$lastDisplayed = false;

foreach ($myarray as $key => $item) {

    // Display first element
    if ($item == $first && !$firstDisplayed) {
        print($item . ": First iteration \n");
        $firstDisplayed = true;
        continue;
    }
    
    // Display last element
    if ($item == $last && !$lastDisplayed && $key == array_key_last($myarray)) {
        print($item . ": Last iteration \n");
        $lastDisplayed = true;
    }
}
?>

Output
1: First iteration 
6: Last iteration 

Method 4: Using Array Keys

Using array keys, you can determine the first iteration in a foreach loop by checking if the current key matches the first key of the array. Similarly, you identify the last iteration by comparing the current key with the last key of the array.

Example: This PHP script identifies and prints the first and last elements of an array by checking if the current key matches the first or last key using array_key_first() and array_key_last().

PHP
<?php
// Declare an array and initialize it
$myarray = array(1, 2, 3, 4, 5, 6);

// Get the first and last keys of the array
$firstKey = array_key_first($myarray);
$lastKey = array_key_last($myarray);

// Loop starts here
foreach ($myarray as $key => $item) {
    // Check if the current key is the first key
    if ($key == $firstKey) {
        print($item);
        print(": First iteration \n");
    }

    // Check if the current key is the last key
    if ($key == $lastKey) {
        print($item);
        print(": Last iteration \n");
    }
}
?>

Output
1: First iteration 
6: Last iteration 

Next Article

Similar Reads