-1

Using the following 2 examples:

foreach($this->fooBar() as $foo => $bar) {
     // do something 
}

versus

$fooBar = $this->fooBar();
foreach($fooBar as $foo => $bar) {
     // do something 
}

Are there any implications of using either over the other or should readability be the only consideration between the two?

5
  • 1
    The only difference is that in the second case, you're keeping the result of the function call accessible after the loop, which both means you can still use it and that it won't be garbage collected. Other than that there's no difference. Commented Jun 24, 2015 at 14:22
  • ...and you use ->fooBar in your first example and ->foo in your second, but that's probably unintentional. Commented Jun 24, 2015 at 14:23
  • Consider also foreach(($fooBar = $this->fooBar()) as $foo => $bar) { Commented Jun 24, 2015 at 14:27
  • 1
    I would recommend against @AbraCadaver's proposal - it is less legible and is somewhat against a "separation of concerns", especially if you use it to access $fooBar after the loop. There's perl for that >;-) Commented Jun 24, 2015 at 14:29
  • @Archimedix: Not a proposal, a consideration. Commented Jun 24, 2015 at 14:30

1 Answer 1

1

It’s basically the same.

In your first example, the result of $this->fooBar() is stored internally.

The second example only makes sense if you also want to use $fooBar outside the foreach loop.

To learn more about internals of PHP’s foreach and why you shouldn’t care too much about the difference between your examples (and similar other ones), have a look at the following article:

https://nikic.github.io/2011/11/11/PHP-Internals-When-does-foreach-copy.html

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.