Using function call in foreach loop

后端 未结 2 884
甜味超标
甜味超标 2020-12-30 19:17

Are there any issues, with regards to efficiency, for using a function call in a foreach loop. For example:

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


        
2条回答
  •  遥遥无期
    2020-12-30 19:39

    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.

提交回复
热议问题