How to use reset() function In PHP

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: 

php
<?php

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

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

// Assign first array element to variable
$first = reset( $myarray );

// Loop starts here
foreach ($myarray as $item) {
    
    // Check if item is equal to first
    // element then it is the first
    // iteration
    if ($item == $first) {
        
        // Display array element
        print( $item );
        print(": First iteration \n");
    }
    
    // If there is no next element 
    // in array then this is last iteration
    if( !next( $myarray ) ) {
        
        // Display array element
        print( $item );
        print(": Last iteration \n");
    }
}
?>

Output
1: First iteration 
6: Last iteration 

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

Given an array of elements and the task is to determine the first and last iteration in the foreach loop. There are many ways to solve this problem which are listed below:

Table of Content

  • Naive method
  • Using reset and end function
  • Using reset() function
  • Using Array Keys

Similar Reads

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....

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....

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....

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....

Contact Us