Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out how many times a foreach construct loops in PHP, without using a "counter" variable?

Tags:

php

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.

like image 477
Titus Avatar asked Jul 14 '11 19:07

Titus


People also ask

How many times does a foreach loop run?

A "Foreach" loop repeats one or more actions on each array item and works only on arrays.

How do I find foreach iteration?

Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration. Example: php.

How many looping techniques are there in PHP?

There are four different types of loops supported by PHP.

Which is faster foreach or for loop in PHP?

The foreach loop is considered to be much better in performance to that of the generic for loop. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.


1 Answers

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.

like image 131
AlexV Avatar answered Oct 07 '22 12:10

AlexV