11

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!

3 Answers 3

12

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any difference in performance if we store it in variable or call the function directly? i mean does php call the function on each iteration?
No PHP won't call the function each loop.
2

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

Comments

0

Simply, yes they are functionally the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.