Using function call in foreach loop

php

Solution

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.

Problem

Are there any issues, with regards to efficiency, for using a function call in a foreach loop. For example: ``` foreach ($this->getValues() as $value) { //Do something with $value } ``` versus ``` $values = $this->getValues(); foreach ($values as $value) { //Do something with $value } ``` Essentially, is php clever enough to call $this->getValues() only once in the first example, or does it call it on each iteration. If it calls it on each iteration, then how does it keep track of which element its currently at,

Original source