7

If I have a foreach construct, like this one:

foreach ($items as $item) {
    echo $item . "<br />";
}

I know I can keep track of how many times the construct loops by using a counter variable, like this:

$counter = 0;

$foreach ($items as $item) {
    echo $item.' is item #'.$counter. "<br />";
    $counter++;
}

But is it possible to do the above without using a "counter" variable? That is, is it possible to know the iteration count within the foreach loop, without needing a "counter" variable?

Note: I'm totally okay with using counters in my loops, but I'm just curious to see if there is a provision for this built directly into PHP... It's like the awesome foreach construct that simplified certain operations which are clunkier when doing the same thing using a for construct.

Titus
  • 4,487
  • 6
  • 32
  • 42

4 Answers4

5

There's no easier way - that's kinda what count variables are for.

I'm assuming that you want to know the current count during the loop. If you just need to know it after, use count($items) as others have suggested.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
5

No it's not possible unless your $items is an array having contiguous indexes (keys) starting with the 0 key.

If it have contiguous indexes do:

foreach ($items as $k => $v)
{
    echo $k, ' = ', $v, '<br />', PHP_EOL;
}

But as others have stated, there is nothing wrong using a counter variable.

AlexV
  • 22,658
  • 18
  • 85
  • 122
  • Thanks. Could you elaborate on PHP_EOL a bit? I looked it up on PHP.net but it didn't really elaborate on the constant. – Titus Jul 14 '11 at 20:02
  • 1
    @Titus Check out my answer in [When do I use the PHP constant “PHP_EOL”?](http://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol/6666554#6666554). – AlexV Jul 14 '11 at 20:05
1

You could tell how many time it WILL loop or SHOULD have looped by doing a

$loops = count($items); 

However that will only work if your code does not skip an iteration in any way.

Dan Smith
  • 5,685
  • 32
  • 33
1

foreach loops N times, where N is just the size of the array. So you can use count($items) to know it.

EDIT Of course, as noticed by Bulk, your loop should not break (or maybe continue, but I would count a continue as a loop, though shorter...)

ShinTakezou
  • 9,432
  • 1
  • 29
  • 39