我怎样才能得到当前的数组索引在foreach循环? [英] How can I get the current array index in a foreach loop?

查看:125
本文介绍了我怎样才能得到当前的数组索引在foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <$ c $ foreach 循环中的当前索引c> foreach($ arr as $ key => $ val)
{
//如何获取索引?
//如何获得关联数组中的第一个元素?


解决方案

只是 $ key



例如,如果您想知道这是第一个,第二个,或者是循环的迭代,这是你唯一的选择:
$ b $ pre $ $ $ $ $ $ $ = 1;
foreach($ arr as $ val){
$ i ++;
// $ i现在是索引。如果$ i == 0,那么这是第一个元素。
...
}

当然,这并不意味着 $ val == $ arr [$ i] 因为数组可能是一个关联数组。


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?
}

解决方案

In your sample code, it would just be $key.

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.
  ...
}

Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.

这篇关于我怎样才能得到当前的数组索引在foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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