How to use reset and end function In PHP
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:
<?php
// PHP program to get first and
// last iteration
// Declare and array and initialize it
$myarray = array( 1, 2, 3, 4, 5, 6 );
// Loop starts here
foreach ( $myarray as $item ) {
// Check item and the return value of
// reset() function is equal then it
// will be the first iteration
if ( $item === reset( $myarray ) ) {
// Display the array element
print( $item );
print(": First iteration \n");
}
// Check if item and return value of
// end() function is equal then it
// will be last iteration
else if( $item === end( $myarray ) ) {
// Display the 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
Contact Us