Using function call in foreach loop

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.

Leave a Comment