Answer the question
In order to leave comments, you need to log in
Sequence number of foreach traversal?
Hi all. Is there some standard way to calculate how many times a foreach loop goes through? Maybe some standard variable stores this value?
So you don't have to write like this:
$i = 0;
foreach($arr as $val) {
// тело цикла
$i++;
}
Answer the question
In order to leave comments, you need to log in
This is the "standard way".
If the array is indexed, and with indices 0, 1, 2, 3..., then it can be simpler:
foreach ($arr as $i => $val) {
// тело цикла
}
foreach (array_values($arr) as $i => $val) {
// тело цикла
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question