2

We all know that in a normal for-loop you should extract the count() out of the loopheader to achieve a better performance, meaning you should use

$size = count($array);
for($i; $i < $size; $i++) {...}

instead of

for($i; $i < count($array); $i++) {...}

to avoid the count()call in every repeat.

But how does foreach works in this case? I'm quite sure that overall it's slower than a for-loop because of the as $key => $value expression handling but that's not what I'm thinking about. I'm interested in the implementation of the "counting" part of the foreach-loop.

Does anyone knows?

Edit: After this question was flaged as a possible duplicate of this question: I don't want to know about the handling of the array cursor, but of the implementation of the counting part.

Community
  • 1
  • 1
bish
  • 3,381
  • 9
  • 48
  • 69
  • 3
    Possible duplicate of [How does 'foreach' actually work?](http://stackoverflow.com/questions/10057671/how-does-foreach-actually-work) – FirstOne Nov 22 '15 at 14:02
  • you might want to make sure that foreach() is significantly slower than for() - it's hardly the case in modern php releases. – Calimero Nov 22 '15 at 14:05

1 Answers1

3

The documentation says:

On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

The next() function

Returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

For simplicity's sake we could say that for array iterations, foreach uses next() internally (or something that has the same effect). There is no count(). An array foreach would be very similar to this:

reset( $array );
do {
   $value = current( $array );
   ...
while ( next( $array ) );
Kenney
  • 9,003
  • 15
  • 21
  • Do I understand it correctly that no `count()` function is used at all? – bish Nov 22 '15 at 14:08
  • Yes, that's my understanding. It works with an internal array pointer; much like a linked list would have a `next` pointer; once that is `null`, say, the iteration is done. – Kenney Nov 22 '15 at 14:14