Home >Backend Development >PHP Tutorial >How to Identify the First and Last Iterations in a PHP Foreach Loop?
How to Differentiate First and Last Iterations in a PHP Foreach Loop
Foreach loops are a common way to iterate through an array in PHP. Sometimes, it is necessary to perform different actions during the first or last iteration. This article provides simple solutions to achieve this in PHP 7.3 and older versions.
PHP 7.3 and Newer
PHP 7.3 introduces the array_key_first() and array_key_last() functions. You can use these functions to check if the current key matches the first or last key of the array:
foreach ($array as $key => $element) { if ($key === array_key_first($array)) { // Code for first element } if ($key === array_key_last($array)) { // Code for last element } }
PHP 7.2 and Older
Prior to PHP 7.3, you can use the reset() and end() functions to determine the first and last keys of the array:
foreach ($array as $key => $element) { reset($array); if ($key === key($array)) { // Code for first element } end($array); if ($key === key($array)) { // Code for last element } }
Note: The solutions provided do not require the initialization of a counter variable outside the loop. They compare the current iteration key against the first or last key of the array.
The above is the detailed content of How to Identify the First and Last Iterations in a PHP Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!