Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to find the foreach index?

Is it likely to discover the foreach index?

in a for loop as follows:

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


$i will give you the list.

Do I need to utilize them for loop or is there some approach to get the index in the foreach loop?
by

2 Answers

akshay1995

foreach($array as $key=>$value) {
// do stuff
}

$key is the index of each $array element
sandhya6gczb
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++;
}

Login / Signup to Answer the Question.