首頁 > 後端開發 > php教程 > 如何在 Foreach 迴圈中存取索引?

如何在 Foreach 迴圈中存取索引?

DDD
發布: 2024-11-14 15:20:02
原創
698 人瀏覽過

How Do You Access the Index in a Foreach Loop?

Unveiling the Index Mystery in Foreach Loops

In a traditional for loop, accessing the current index is straightforward with variables like $i. However, this convenience seems to vanish in foreach loops. Can we uncover that hidden index for foreach iteration?

The answer lies in the syntax of foreach loops. Unlike for loops, foreach operates based on a key-value mapping. Each element in the iterated array or object is assigned a key and a value.

Eureka! The Truth Revealed

The secret to accessing the foreach index lies within the $key variable. Every time a foreach loop encounters an element, it assigns a unique key to it. This key represents the element's index or position within the collection.

Example Illumination

Let's consider the following array:

$array = ['apple', 'banana', 'cherry'];
登入後複製

Using a foreach loop to iterate through this array:

foreach ($array as $key => $value) {
    // $key contains the index of the current element
    echo "Index: $key, Value: $value\n";
}
登入後複製

As you can see, the $key variable holds the index of the element. In this example, the output would be:

Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: cherry
登入後複製

So, while $i remains the trusty index guide in for loops, embrace $key as the key to unlocking the index mystery in foreach loops.

以上是如何在 Foreach 迴圈中存取索引?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板