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:
<?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
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
Contact Us