Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function return result into a foreach loop

Tags:

php

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!

like image 572
Sherms Avatar asked Jun 09 '11 23:06

Sherms


People also ask

Can we use return in forEach loop?

You can't make JavaScript's forEach() function return a custom value. Using return in a forEach() is equivalent to a continue in a conventional loop.

Does return stop a forEach?

'return' doesn't stop looping The reason is that we are passing a callback function in our forEach function, which behaves just like a normal function and is applied to each element no matter if we return from one i.e. when element is 2 in our case.


1 Answers

Yes, they are basically equivalent.

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

like image 55
Petah Avatar answered Oct 25 '22 12:10

Petah