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

lov*_*ing 36 php syntax foreach

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

foreach ($arr as $key => $val)
{
    // How do I get the index?
    // How do I get the first element in an associative array?
}
Run Code Online (Sandbox Code Playgroud)

Kip*_*Kip 58

在您的示例代码中,它只是$key.

如果你想知道,例如,如果这是循环的第一次,第二次或 i 迭代,这是你唯一的选择:

$i = -1;
foreach($arr as $val) {
  $i++;
  //$i is now the index.  if $i == 0, then this is the first element.
  ...
}
Run Code Online (Sandbox Code Playgroud)

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

  • @pbarney我不同意.在最后执行增量是一个等待发生的错误:如果循环体中有任何`continue;`语句,或者任何人可能在将来合理地添加一个语句,则最后的增量不起作用.此外,这使变量的声明和增量保持接近. (5认同)
  • 也许从$ i = 0;开始,然后将$ i ++;增量器移到循环的底部以提高可读性。 (2认同)

Fab*_*ert 15

到目前为止,这是最详尽的答案,并且不需要$i变量浮动.这是Kip和Gnarf答案的组合.

$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_keys( $array ) as $index=>$key ) {

    // display the current index + key + value
    echo $index . ':' . $key . $array[$key];

    // first index
    if ( $index == 0 ) {
        echo ' -- This is the first element in the associative array';
    }

    // last index
    if ( $index == count( $array ) - 1 ) {
        echo ' -- This is the last element in the associative array';
    }
    echo '<br>';
}
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助某人.

  • 创建一个长度为“count($array)”的全新数组似乎需要很大的开销,以避免引入一个标量变量 (2认同)
  • array_keys是我的解决方案,谢谢! (2认同)
  • 非常糟糕的命名`$index=&gt;$key` (2认同)

cle*_*tus 11

$i = 0;
foreach ($arr as $key => $val) {
  if ($i === 0) {
    // first index
  }
  // current index is $i

  $i++;
}
Run Code Online (Sandbox Code Playgroud)


Xma*_*cal 8

foreach($array as $key=>$value) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

$ key是每个$数组元素的索引

  • 不是必须的.如果您的数组看起来像这样:`$ array = array('cat'=>'meow','dog'=>'woof','cow'=>'moo','computer'=>'beep'); `第一项的$键是'cat'. (4认同)

小智 5

当前索引是 的值$key。对于另一个问题,您还可以使用:

current($arr)
Run Code Online (Sandbox Code Playgroud)

获取任何数组的第一个元素,假设您没有使用next(),prev()或其他函数来更改数组的内部指针。