Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a difference when putting a function call in a foreach loop vs the result in a variable?

Tags:

foreach

php

Is there any difference in behaviour between

foreach(anyfunction($array) as $value){ //...do something

and

$values = anyfunction($array);
foreach($values as $value){//...do something

I am 99% sure that there is not a difference, however when looking into source codes of open source projects I mainly find the second variant.

like image 424
Moak Avatar asked Oct 01 '22 12:10

Moak


1 Answers

It's a scope thing. The temporary variable generated by the function_call() use should (not 100% how the garbage collector works in PHP but I'm 99% sure memory is freed when the loop ends) be discarded once the loop ends. The $values will live longer.

It's all a question of whether you need it to outlive your loop. If you don't, unset($values) manually after the loop (or when you no longer need it) or just use it as a function call in the loop.

If $values takes a bit of memory and is not needed outside the loop, then go for the 1st variant. It's not a matter of readability as long as your function name is meaningful.

PS: In C++ we sometimes control variable scope with arbitrary {...} inside code as variables created after { are destroyed when the } hits.

like image 173
CodeAngry Avatar answered Oct 18 '22 10:10

CodeAngry