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

40

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

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

20
$key 是当前索引。 - jason
10个回答

67
在您的示例代码中,这只是$key
如果您想知道,例如,这是循环的第一次、第二次还是第i次迭代,这是您唯一的选择:
$i = -1;
foreach($arr as $val) {
  $i++;
  //$i is now the index.  if $i == 0, then this is the first element.
  ...
}

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


3
也许可以从 $i = 0; 开始,然后把 $i++; 的累加器移到循环底部以提高可读性。 - pbarney
7
我不同意。在循环末尾进行增量操作会引发潜在的问题:如果循环体中存在任何 continue; 语句,或者将来可能有人合理地添加这样的语句,那么在循环末尾进行增量操作就无法正常工作。此外,这样做可以使变量的声明和增量操作更加靠近。 - Kip

16

目前为止,这是最详尽的答案,并且消除了需要一个漂浮的$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>';
}

希望这可以帮助到某个人。


2
创建一个长度为 count($array) 的全新数组似乎有很多额外开销,只为了避免引入一个标量变量。 - Kip
3
非常糟糕的命名 $index=>$key - dompie

12
foreach($array as $key=>$value) {
    // do stuff
}

$key是每个$array元素的索引。


5
不一定。如果您的数组长这样:$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );,那么第一项的$key将是'cat'。 - Andrew Cavanagh
谢谢您的回复。我认为索引会是关键。这里有:“猫”,“狗” ... - Xman Classical
1
我不明白为什么这不是此页面上最佳答案。 - Syed Priom

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

  $i++;
}

5

当前索引的值为$key。至于另一个问题,你也可以使用:

current($arr)

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


1
+1作为索引不一定是整数:http://en.wikipedia.org/wiki/Index#Computer_science - Mathias

3

通过以下方式,您可以获取索引值:

foreach ($arr as $key => $val)
{
    $key = (int) $key;
    //With the variable $key you can get access to the current array index
    //You can use $val[$key] to

}

0

$key 是当前数组元素的索引,而 $val 是该数组元素的值。

第一个元素的索引为0。因此,要访问它,请使用 $arr[0]

要获取数组的第一个元素,请使用以下内容:

$firstFound = false;
foreach($arr as $key=>$val)
{
    if (!$firstFound)
       $first = $val;
    else
       $firstFound = true;
    // do whatever you want here
}

// now ($first) has the value of the first element in the array

0
你也可以使用 array_keys() 函数获取第一个元素。或者使用array_search()查找键的“索引”。如果你在一个 foreach 循环中,kip 或 cletus 建议使用简单的增量计数器,这可能是最有效的方法。
<?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)

0

好的,既然这是这个问题的首个谷歌搜索结果:

function mb_tell(&$msg) {
    if(count($msg) == 0) {
        return 0;
    }
    //prev($msg);
    $kv = each($msg);
    if(!prev($msg)) {
        end($msg);

        print_r($kv);
        return ($kv[0]+1);
    }
    print_r($kv);
    return ($kv[0]);
}

0

基于 @fabien-snauwaert 的答案,但如果您不需要原始密钥,则进行了简化

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

    // display the current index +  value
    echo $index . ':' . $value;

    // 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>';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接