Jac*_*ero 0 php foreach continue
这似乎是一个非常愚蠢的问题,但没有对服务器进行任何更改.. PHP中的continue函数似乎已经开始正常工作.
例如:
function contTest(){
$testers = array(1, 3, 4, 5);
foreach($testers as $test){
echo "Got here<br>";
continue;
echo $test."<br>";
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Got here
Got here
Got here
Got here
Run Code Online (Sandbox Code Playgroud)
鉴于:
function contTest(){
$testers = array(1, 3, 4, 5);
foreach($testers as $test){
echo "Got here<br>";
echo $test."<br>";
}
}
Run Code Online (Sandbox Code Playgroud)
.OUPUTS:
Got here
1
Got here
3
Got here
4
Got here
5
Run Code Online (Sandbox Code Playgroud)
我之前使用过这个功能,似乎没有这个效果.有任何想法吗?就像我说的那样,服务器上的任何内容都没有改变,因此PHP版本是相同的.
我想你需要了解继续如何运作.我想添加一些,所以如果其他人面对相同,可能会有这个作为参考.
您需要使用关键字 continue 当您想要忽略循环的下一次迭代时.continue is always used with if condition
根据这里的例子.
function contTest(){
$testers = array(1, 3, 4, 5);
foreach($testers as $test){
echo "Got here<br>";
**continue;**
echo $test."<br>";
}
}
Run Code Online (Sandbox Code Playgroud)
这符合预期和完美,这就是原因.你循环遍历数组$ testers,里面有四个元素,在获取每个元素后,你告诉php使用continue忽略元素 ,这就是为什么它不会输出数组$ testers的元素的原因.
让我试着在这里重写你的例子.
function contTest(){
$testers = array(1, 3, 4, 5);
foreach($testers as $test){
echo "Got here<br>";
if ($test == 1):
continue;
endif;
echo $test."<br>";
}
}
echo contTest();
Run Code Online (Sandbox Code Playgroud)
我刚刚使用continueif if等于1,这意味着该元素将被跳过(忽略).输出是:
Got here
Got here
3
Got here
4
Got here
5
Run Code Online (Sandbox Code Playgroud)
如你所见,1被忽略了.