如何在 foreach 循环中获取当前数组索引? [英] How can I get the current array index in a foreach loop?

查看:67
本文介绍了如何在 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 循环中获取当前数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆