How to find the foreach index?

user18334 picture user18334 · Sep 26, 2008 · Viewed 706.9k times · Source

Is it possible to find the foreach index?

in a for loop as follows:

for ($i = 0; $i < 10; ++$i) {
   echo $i . ' ';
}

$i will give you the index.

Do I have to use the for loop or is there some way to get the index in the foreach loop?

Answer

Owen picture Owen · Sep 26, 2008
foreach($array as $key=>$value) {
    // do stuff
}

$key is the index of each $array element