tags:

views:

90

answers:

3
foreach(func() as $item)...

The above will only call func() once,but why?What's happening exactly?

+1  A: 

There's no need to call the function more than once - it should return an array that can be iterated over.

middaparka
+7  A: 

foreach accepts an array. You are essentially calling func() once yourself, and passing the resulting array to the foreach construct, which can loop over it.

Tom Haigh
Can you prove it?
I think its evident when you evaluate the `foreach` loop
Anthony Forloney
to prove it add an echo or log to the function you call in `func()`
thetaiko
@user198729: You could "prove it" yourself if you ever cared to look at the PHP manual.
Johannes Gorset
phenomenon is not evidence
Evidence is anything that you see, experience, read, or are told that causes you to believe that something is true or has really happened
thetaiko
"phenomenon is not evidence"I will upvote your question if you prove it exists.
koen
+2  A: 

foreach is not a control structure with a condition that is tested before or after each iteration like while, for or do … while. Instead it takes an array, makes an copy of it internally and iterates that.

The array can either be passed via a variable (most used variant):

foreach ($arr as $val) { /* … */ }

Or with another expression that returns an array when evaluated:

foreach (array('foo','bar') as $val) { /* … */ }

function f() { return array('foo','bar'); }
foreach (f() as $val) { /* … */ }
Gumbo
It's not a structure,what is it?
http://www.php.net/foreach
Johannes Gorset
@user198729: I didn’t say it’s not a control structure. I just said it’s not a control structure with a condition that’s tested on every iteration.
Gumbo