Given an array of elements and the task is to determine first and last iteration in foreach loop. There are many ways to solve this problem which are listed below:
Method 1: It is the naive method inside foreach 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:
php
<?php
$myarray = array ( 1, 2, 3, 4, 5, 6 );
$counter = 0;
foreach ( $myarray as $item ) {
if ( $counter == 0 ) {
print ( $item );
print ( ": First iteration \n" );
}
if ( $counter == count ( $myarray ) - 1) {
print ( $item );
print ( ": Last iteration" );
}
$counter = $counter + 1;
}
?>
|
Output
1: First iteration
6: Last iteration
Method 2: 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:
php
<?php
$myarray = array ( 1, 2, 3, 4, 5, 6 );
foreach ( $myarray as $item ) {
if ( $item === reset( $myarray ) ) {
print ( $item );
print ( ": First iteration \n" );
}
else if ( $item === end ( $myarray ) ) {
print ( $item );
print ( ": Last iteration \n" );
}
}
?>
|
Output
1: First iteration
6: Last iteration
Method 3: 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
$myarray = array ( 1, 2, 3, 4, 5, 6 );
$first = reset( $myarray );
foreach ( $myarray as $item ) {
if ( $item == $first ) {
print ( $item );
print ( ": First iteration \n" );
}
if ( !next( $myarray ) ) {
print ( $item );
print ( ": Last iteration \n" );
}
}
?>
|
Output
1: First iteration
6: Last iteration
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Apr, 2023
Like Article
Save Article