How to find the foreach index?
Solution 1:
foreach($array as $key=>$value) {
// do stuff
}
$key
is the index of each $array
element
Solution 2:
You can put a hack in your foreach
, such as a field incremented on each run-through, which is exactly what the for
loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).
A foreach
will give you your index in the form of your $key
value, so such a hack shouldn't be necessary.
e.g., in a foreach
$index = 0;
foreach($data as $key=>$val) {
// Use $key as an index, or...
// ... manage the index this way..
echo "Index is $index\n";
$index++;
}
Solution 3:
It should be noted that you can call key()
on any array to find the current key its on. As you can guess current()
will return the current value and next()
will move the array's pointer to the next element.
Solution 4:
Owen has a good answer. If you want just the key, and you are working with an array this might also be useful.
foreach(array_keys($array) as $key) {
// do stuff
}