In the following code:
function a(){ echo 'a'; return array(1,2,3,4); } foreach(a() as $t){ echo $t; }
We can see a() is called only once, and it seems the returned value is cached...
But then I got to see this debate (see comments on the question) am I missing something?
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain. forEach() does not mutate the array on which it is called. (
The foreach loop is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to $value, and the array pointer is advanced by one to go the next element in the array.
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
No, your test is conclusive.
It makes no sense for it to evaluate the first expression any more than once. It's the basic premise of a foreach loop.
A for
loop has three arguments, and it does evaluate the second and third each iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With