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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1450157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:37:43  来源:igfitidea点击:

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

phpsyntaxforeach

提问by lovespring

How do I get the current index in a foreachloop?

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

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

回答by Kip

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

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

If you want to know, for example, if this is the first, second, or ithiteration of the loop, this is your only option:

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

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

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

回答by Fabien Snauwaert

This is the most exhaustive answer so far and gets rid of the need for a $ivariable floating around. It is a combo of Kip and Gnarf's answers.

这是迄今为止最详尽的答案,并且不需要$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>';
}

Hope it helps someone.

希望它可以帮助某人。

回答by cletus

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

  $i++;
}

回答by Xman Classical

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

$keyis the index of each $arrayelement

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

回答by Eduardo Grajeda

The current index is the value of $key. And for the other question, you can also use:

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

current($arr)

to get the first element of any array, assuming that you aren't using the next(), prev()or other functions to change the internal pointer of the array.

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

回答by khrizenriquez

You can get the index value with this

您可以使用此获取索引值

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

}

回答by Sébastien Leprovost

based on @fabien-snauwaert's answer but simplified if you do not need the original key

基于@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>';
}

回答by gnarf

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 foreachloop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.

您也可以获取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)

回答by user1820381

well since this is the first google hit for this problem:

好吧,因为这是这个问题的第一个谷歌命中:

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]);
}

回答by Aziz

$keyis the index for the current array element, and $valis the value of that array element.

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

The first element has an index of 0. Therefore, to access it, use $arr[0]

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

To get the first element of the array, use this

要获取数组的第一个元素,请使用此

$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