如何在 foreach 循环中获取当前数组索引?

2021-12-26 00:00:00 syntax foreach php

如何在 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.

相关文章