How can I get the current array index in a foreach loop?

前端 未结 10 1720
陌清茗
陌清茗 2020-12-14 06:19

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 fir         


        
10条回答
  •  粉色の甜心
    2020-12-14 06:38

    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.

提交回复
热议问题