Return from loop 但是执行循环没有效果?

Return from loop but the execution of loop not effects?

在 php 中是可能的,当 return 来自循环的一些值和循环的执行仍然从下一个索引继续(如 C# 中的 GetEnumerator() 和使用 MoveNext())

问题-

$arr=[0,1,5,9,5];
$i=count($arr);
while($i>0){
    // data base operations
    $_GLOBALS['i']=$_GLOBALS['i']-1;
    //return some value;
}

我是一名 C# 程序员,并且是 php 的新手,所以任何帮助或想法都将不胜感激?

Return 作为控制结构 return 可以在函数(过程)或方法(面向对象)中使用 return 一个值,但这是可选的。如果你有一个循环 whilefor foreach 等,并且你在其中使用 return,那么这会将 return 值传递给调用模块并停止循环。

但是有一些方法可以执行循环并 return 将其移交给静态对象或全局变量。

其实你可以。您正在寻找的是 yield keyword from C#. According to the php documentation 的等效项,可以在 php 中使用相同的关键字来实现生成器。

文档页面上有一个小例子:

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\n";
}

The above example will output:

1
2
3