是否有可能找到foreach索引?

在for循环中如下所示:

for ($i = 0; $i < 10; ++$i) {
   echo $i . ' ';
}

$i会给你索引。

我必须使用for循环还是有一些方法在foreach循环中获得索引?


当前回答

这两个循环是等价的(当然除了安全栏杆):

for ($i=0; $i<count($things); $i++) { ... }

foreach ($things as $i=>$thing) { ... }

eg

for ($i=0; $i<count($things); $i++) {
    echo "Thing ".$i." is ".$things[$i];
}

foreach ($things as $i=>$thing) {
    echo "Thing ".$i." is ".$thing;
}

其他回答

我通常在使用关联数组时这样做:

foreach ($assoc_array as $key => $value) {
 //do something
}

这也适用于非关联数组。$key将是索引值。如果你喜欢,你也可以这样做:

foreach ($array as $indx => $value) {
  //do something
}

你可以在循环外创建$i,并在循环底部执行$i++。

欧文有一个很好的答案。如果你只想要一个键,并且你正在处理一个数组,这可能也是有用的。

foreach(array_keys($array) as $key) {
//  do stuff
}

需要注意的是,您可以在任何数组上调用key()来查找当前所在的键。正如你所猜测的,current()将返回当前值,next()将移动数组的指针到下一个元素。

当我必须在同一个上下文中使用foreach索引和值时,我用这种方法解决了:

$array = array('a', 'b', 'c');
foreach ($array as $letter=>$index) {

  echo $letter; //Here $letter content is the actual index
  echo $array[$letter]; // echoes the array value

}//foreach