Determine the first and last iteration in a foreach loop in PHP?
Last Updated :
19 Sep, 2024
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;
}
?>
Output1: 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;
}
}
?>
Output1: 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;
}
}
?>
Output1: 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");
}
}
?>
Output1: First iteration
6: Last iteration
Similar Reads
Get the First & Last Item from an Array in PHP
We will get the first and last elements of an array in PHP. This can be particularly useful in scenarios like processing data, working with queues, or implementing specific algorithms. Below are the approaches to get the first and last items from an array in PHP: Table of Content Using Array Indexin
2 min read
Iterate associative array using foreach loop in PHP
Given two arrays arr1 and arr2 of size n. The task is to iterate both arrays for each loop. Both arrays can combine into a single array using a for each loop. Array: Arrays in PHP are a type of data structure that allows the storing of multiple elements of similar data type under a single variable t
3 min read
How to Get first N number of Elements From an Array in PHP?
Given an array, the task is to get the first N number of elements from the array in PHP. There are various approaches to achieve this task. In this article, we will explore all approaches with detailed explanations.These are the following approaches:Table of Content Using array_slice() FunctionUsing
3 min read
PHP Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1The approach is very
2 min read
Find First and Last Digits of a Number in PHP
Given a Number, the task is to find the first, and last digits of a number using PHP. Examples: Input: num = 145677Output: First Digit: 1, and Last Digit: 7Input: 101130Output: First Digit: 1, and Last Digit: 0There are three methods to get the first and last digit of number, these are: Table of Con
2 min read
Swipe First & Last Element of an Array in PHP
Swapping the first and last elements of an array is a common operation that can be useful in various scenarios, such as rearranging data or preparing it for specific algorithms. Below are the approaches to swipe the first and last element of an array in PHP: Table of Content Using Temporary Variable
3 min read
How to Find the Largest Element in an Array in PHP?
Given an array containing some elements, the task is to find the largest element from an array in PHP. PHP provides several ways to achieve this, each with its own advantages and use cases. Below are the approaches to find the largest element in an array in PHP:Table of ContentUsing max() FunctionUs
4 min read
How to find the index of foreach loop in PHP ?
The foreach construct provides the easiest way to iterate the array elements. It works on array and objects both. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively. It allocates temporary memory for index iteratio
3 min read
Find the Majority Element of an Array in PHP
We will create a PHP array of integers i.e. $num1 or $num2 and find the element in an array that appears more than n/2 times, where n is the length of the array. The element that appears more than n/2 times will indicate the majority element in the array. These problems in PHP help users solve appli
4 min read
How to get the First Element of an Array in PHP?
Accessing the first element of an array in PHP is a common task, whether they are indexed, associative, or multidimensional. PHP provides various methods to achieve this, including direct indexing, and built-in functions.Below are the approaches to get the first element of an array in PHP:Table of C
4 min read