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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With