Home > Backend Development > PHP Tutorial > How can I access the index of elements within a PHP foreach loop?

How can I access the index of elements within a PHP foreach loop?

Patricia Arquette
Release: 2024-11-12 09:53:02
Original
497 people have browsed it

How can I access the index of elements within a PHP foreach loop?

Finding the Index in a Foreach Loop

Similar to the for loop, the foreach loop in PHP also allows you to access the index of the current element. Unlike the for loop, however, the foreach loop uses a different syntax to expose this information.

The syntax for a basic foreach loop is as follows:

foreach($array as $key=>value) {
    // do stuff
}
Copy after login

In this syntax, the $key variable holds the index of each element in the $array. This index can be used to access the element's corresponding value in the $value variable.

Example

consider the following foreach loop:

$fruits = ['apple', 'banana', 'cherry', 'durian'];

foreach($fruits as $index=>$fruit) {
    echo 'Fruit ' . $index . ': ' . $fruit . PHP_EOL;
}
Copy after login

In this example, the $index variable holds the index of each fruit element in the $fruits array. The loop outputs the index and the corresponding fruit value on each line, resulting in the following output:

Fruit 0: apple
Fruit 1: banana
Fruit 2: cherry
Fruit 3: durian
Copy after login

The above is the detailed content of How can I access the index of elements within 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