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?
}
This is the most exhaustive answer so far and gets rid of the need for a
$i
variable floating around. It is a combo of Kip and Gnarf's answers.Hope it helps someone.
based on @fabien-snauwaert's answer but simplified if you do not need the original key
The current index is the value of
$key
. And for the other question, you can also use:to get the first element of any array, assuming that you aren't using the
next()
,prev()
or other functions to change the internal pointer of the array.You can get the index value with this
$key
is the index for the current array element, and$val
is the value of that array element.The first element has an index of 0. Therefore, to access it, use$arr[0]
To get the first element of the array, use this
well since this is the first google hit for this problem: