Is the array creation happening on every foreach loop? [closed]

No, neither language splits the string every time (that would be absurd).

From the PHP manual:

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).

Note the reference to the internal array pointer. If each iteration operated on a distinct array, changing the internal array pointer would be meaningless.

From the ES5 annotated reference:

When the forEach method is called with one or two arguments, the
following steps are taken:

  1. Let O be the result of calling ToObject passing the this value as the argument.

Here O represents the object being iterated on; this result is only calculated once.

Leave a Comment