How can I get the current array index in a foreach

2020-02-08 06:44发布

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

10条回答
Anthone
2楼-- · 2020-02-08 07:34

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.

查看更多
Evening l夕情丶
3楼-- · 2020-02-08 07:39

You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.

<?php
   $array = array('test', '1', '2');
   $keys = array_keys($array);
   var_dump($keys[0]); // int(0)

   $array = array('test'=>'something', 'test2'=>'something else');
   $keys = array_keys($array);

   var_dump(array_search("test2", $keys)); // int(1)     
   var_dump(array_search("test3", $keys)); // bool(false)
查看更多
Deceive 欺骗
4楼-- · 2020-02-08 07:40
$i = 0;
foreach ($arr as $key => $val) {
  if ($i === 0) {
    // first index
  }
  // current index is $i

  $i++;
}
查看更多
Explosion°爆炸
5楼-- · 2020-02-08 07:40
foreach($array as $key=>$value) {
    // do stuff
}

$key is the index of each $array element

查看更多
登录 后发表回答