A
A
Alexey2015-11-14 01:11:11
PHP
Alexey, 2015-11-14 01:11:11

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

1 answer(s)
C
Cat Anton, 2015-11-14
@dzheka3d

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) {
    // тело цикла
}

If the array is associative but you don't need its keys:
foreach (array_values($arr) as $i => $val) {
    // тело цикла
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question