如何在 foreach 循环中获取当前数组索引?
如何在循环中获取当前索引?foreach
foreach ($arr as $key => $val)
{
    // How do I get the index?
    // How do I get the first element in an associative array?
}
如何在循环中获取当前索引?foreach
foreach ($arr as $key => $val)
{
    // How do I get the index?
    // How do I get the first element in an associative array?
}
在您的示例代码中,它只是 .$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]
这是迄今为止最详尽的答案,并且不需要浮动的变量。这是基普和格纳夫答案的组合。$i
$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>';
}
希望它能帮助别人。
 
				    		 
				    		 
				    		 
				    		