本文介紹了如何在 foreach 循環中獲取當前數組索引?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如何在 foreach
循環中獲取當前索引?
How do I get the current index in a foreach
loop?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
推薦答案
在您的示例代碼中,它只是 $key
.
In your sample code, it would just be $key
.
例如,如果您想知道這是循環的第一次、第二次或 ith 次迭代,這是您唯一的選擇:
If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:
$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}
當然,這并不意味著 $val == $arr[$i]
因為數組可以是關聯數組.
Of course, this doesn't mean that $val == $arr[$i]
because the array could be an associative array.
這篇關于如何在 foreach 循環中獲取當前數組索引?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!