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

标签 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?
}

最佳答案

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

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

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

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

关于php - 如何在 foreach 循环中获取当前数组索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1450157/

相关文章:

php - PHP-FFMpeg 未转换后(ffmpeg 错误)

php - 是否可以只搜索一页?

php - Ext.需要 php 文件

c# - 新表达式需要 ()、[] 或 {} C# 构造函数错误

Mysql 5.0 存储过程语法

php - PHP 中单引号和双引号字符串有什么区别?

java - 这在 Java 中意味着什么?

php - 如何通过从另一个下拉列表中选择值来填充下拉列表?

r - 使用 doparallel 在 foreach 循环内循环

php - 使 foreach 循环中的 $id 唯一