Is is possible in php when return some value from loop and execution of loop still continues from next index (like GetEnumerator() in C# and the use MoveNext())
problem-
$arr=[0,1,5,9,5];
$i=count($arr);
while($i>0){
// data base operations
$_GLOBALS['i']=$_GLOBALS['i']-1;
//return some value;
}
I am a c# programmer and new to php so any help or ideas would be highly appreciated ?
Return as the Control Structures return
can be used in a function (procedural) or method (Object oriented) to return a value, but this is optional. If you have a loop while
, for
foreach
etc. and you use return
within, than this would return the value to the calling module and stops the loop.
But there are ways to do a loop and instate of returning it hand it over to a static Object or a global variable.
Actually you can. What you are looking for is the equivalent of the yield
keyword from C#. According to the php documentation, the same keyword can be used in php to implement a generator.
There is a small example on the documentation page:
function gen_one_to_three() { for ($i = 1; $i <= 3; $i++) { // Note that $i is preserved between yields. yield $i; } } $generator = gen_one_to_three(); foreach ($generator as $value) { echo "$value "; }
The above example will output:
1 2 3