foreach(func() as $item)...
The above will only call func()
once,but why?What's happening exactly?
foreach(func() as $item)...
The above will only call func()
once,but why?What's happening exactly?
There's no need to call the function more than once - it should return an array that can be iterated over.
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.
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) { /* … */ }