简体   繁体   中英

Passing a function return result into a foreach loop

Out of curiosity, are the two options below functionally equivalent?

$array_variable = function_that_creates_an_array();
foreach($array_variable as $a){
    do_something()
}

vs.

foreach(function_that_creates_an_array() as $a){
    do_something()
}

Just want to make sure I'm not calling the function on every iteration or anything dumb like that.

Thanks!

Yes, they are basically equivalent.

The only difference is the first one will add a variable to the current scope (ie if your in the global scope).

The two snippet will read the array the same way, without re-evaluation the function.

Nevertheless, in the second snippet, you will not be able to access to the complete array during the loop since you don't have any reference (variable) on it.

http://www.php.net/manual/en/control-structures.foreach.php

Simply, yes they are functionally the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM