Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using a function in foreach loop caches the result, or calls the function each time?

Tags:

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?

like image 251
Itay Moav -Malimovka Avatar asked Dec 12 '09 01:12

Itay Moav -Malimovka


People also ask

What does forEach returns?

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

What is the function of forEach loop?

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.

Which one is faster for or forEach?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


1 Answers

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.

like image 100
gahooa Avatar answered Oct 21 '22 12:10

gahooa