Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function call in foreach loop

Tags:

php

People also ask

How do you execute a function in a for loop?

var condition; do { console. log((function(){})()); // output: undefined } while (condition); With a defined condition and a way to toggle it in the loop body, the function can be run as many times as we wish. In this demo, the output is expected since the return value of a function, when not specified, is undefined .

Is forEach a callback function?

The forEach() method calls a specified callback function once for every element it iterates over inside an array.

Does forEach pass reference?

This is an example why pass-by-reference in foreach loops is BAD. This is because when the second loop executes, $entry is still a reference. Thus, with each iteration the original reference is overwritten.


These are both essentially the same:

foreach ($this->getValues() as $value) {
 //
}

$values = $this->getValues();
foreach ($values as $value) {
  //
}

$this->getValues() will only run once, as it is not inside the loop itself. If you need to use the return value of getValues again later, go ahead and assign it to a variable so you don't have to call the function again. If not, you don't really need a variable.


There may be a difference, but it is going to be negligible for 99.9% of real-world cases. In either case, PHP will call your function/method only once. What happens internally when you use foreach is that PHP evaluates the iteratee (the part before the as) once, stores the result, and then loops over it, putting the current element into the local variable given after the as. If you write the iteratee to a local variable yourself, you are practically just duplicating PHP's effort, so the first approach may carry an extra overhead, but it's not going to be enough to worry about. I'd optimize for readability instead: if the function call is short and self-describing, inline it; if it's complex or obscure, store it in a descriptive variable instead.

Note that the situation is different with typical for and while loops, which is probably where you got this notion from. For example, in the following code:

for ($number = 0; $number < $this->getNumberOfItems(); ++$number) {
    // do stuff...
}

...the getNumberOfItems() method gets called on every iteration. In this situation, it makes sense to precalculate it and store it in a local variable.