1

我正在使用这样的 php foreach 语句:

<?php foreach($files as $f): ?>

大量的 HTML

<?php endforeach; ?>

我怎样才能在循环中放置一个条件,以便它可以跳到下一次迭代。我知道我应该使用 continue,但我不确定如何使用这样的封闭 php 语句来做到这一点。它会是一个单独的php语句吗?是否可以将其放置在 HTML 的中途,以便执行循环中的部分但不是全部内容?

4

2 回答 2

3

是的,您可以在任意位置插入条件continue

<?php foreach($files as $f): ?>

lots of HTML

<?php if (condition) continue; ?>

more HTML

<?php endforeach; ?>

看到它在行动

于 2012-08-30T22:42:41.677 回答
0

我有一个非常相似的问题,所有搜索都把我带到了这里。希望有人发现我的帖子有用。从我自己的代码:对于 PHP 5.3.0,这有效:

foreach ($aMainArr as $aCurrentEntry) {
    $nextElm = current($aMainArr); //the 'current' element is already one element ahead of the already fetched but this happens just one time!
    if ($nextElm) {
        $nextRef = $nextElm['the_appropriate_key'];
        next($aMainArr); //then you MUST continue using next, otherwise you stick!
    } else { //caters for the last element
    further code here...
    }
//further code here which processes $aMainArr one entry at a time...
}

对于 PHP 7.0.19,以下工作:

reset($aMainArr);
foreach ($aMainArr as $aCurrentEntry) {
    $nextElm = next($aMainArr);
    if ($nextElm) {
        $nextRef = $nextElm['the_appropriate_key'];
    } else { //caters for the last element
    further code here...
    }
//further code here which processes $aMainArr one entry at a time...
}
于 2018-05-10T08:52:27.487 回答