Home > Backend Development > PHP Tutorial > How to Identify the First and Last Iterations in a PHP Foreach Loop?

How to Identify the First and Last Iterations in a PHP Foreach Loop?

Linda Hamilton
Release: 2024-12-09 10:38:06
Original
650 people have browsed it

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
    }
}
Copy after login

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
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template