如何在 foreach
循环中获取当前索引?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
最佳答案
在您的示例代码中,它只是$key
。
如果您想知道,例如,这是循环的第一次、第二次还是第 ith 次迭代,这是您唯一的选择:
$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}
当然,这并不意味着 $val == $arr[$i]
因为数组可以是关联数组。
关于php - 如何在 foreach 循环中获取当前数组索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1450157/