2

I see plenty of code examples where the user is returning from within a foreach loop, but is it bad form to do this? Does it leave any orphaned references, for example?

Here's an example:

$array = array(1, 2, 4, 8, 16);    
foreach ($array as $value) {
  if ($value == 8) return true; 
}
return false;

EDIT: This is quite different from its supposedly duplicate question, simply by the fact that it focuses on the return instruction, not the break, continue, goto, or any other instruction. Users who are searching for the answer to this question will no necessarily search for the supposed alternatives. In my case, it didn't event occur to me to think them through. Even if I had I would not have come up with an exhaustive list.

DatsunBing
  • 8,684
  • 17
  • 87
  • 172
  • What do you mean by "orphaned reference"? – Alexander O'Mara Oct 31 '14 at 03:38
  • @wolfgangwalther I don't think this is a duplicate, that question talks about using `break`, not `return`. – Alexander O'Mara Oct 31 '14 at 03:40
  • 1
    @AlexanderO'Mara same concept though – Phil Oct 31 '14 at 03:40
  • 1
    To answer your question: no, it does not leave any "orphaned references". PHP is a memory managed, garbage collecting language; its garbage collection is triggered when a scope ends, which mostly means when a function returns. It doesn't matter when or where or how the function returns (`return`, `exit`, `throw`, crash etc.), it will always get cleaned up. – deceze Oct 31 '14 at 06:47

0 Answers0