本文介紹了如何在 foreach 循環(huán)中獲取當(dāng)前數(shù)組索引?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
如何在 foreach
循環(huán)中獲取當(dāng)前索引?
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
.
例如,如果您想知道這是循環(huán)的第一次、第二次或 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.
...
}
當(dāng)然,這并不意味著 $val == $arr[$i]
因?yàn)閿?shù)組可以是關(guān)聯(lián)數(shù)組.
Of course, this doesn't mean that $val == $arr[$i]
because the array could be an associative array.
這篇關(guān)于如何在 foreach 循環(huán)中獲取當(dāng)前數(shù)組索引?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!