gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:01:35 26 4
gpt4 key购买 nike

如何在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com