How do I get the current index in a foreach
loop?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
How do I get the current index in a foreach
loop?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
In your sample code, it would just be
$key
.If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:
Of course, this doesn't mean that
$val == $arr[$i]
because the array could be an associative array.You could get the first element in the
array_keys()
function as well. Orarray_search()
the keys for the "index" of a key. If you are inside aforeach
loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.$key is the index of each $array element