我使用的php foreach语句如下:
<?php foreach($files as $f): ?>大量的HTML
<?php endforeach; ?>我怎样才能把一个条件放在循环里面,这样它就会跳到下一个迭代。我知道我应该使用continue,但我不确定如何使用像这样的封闭php语句。这会是一个单独的php声明吗?是否可以将它放在HTML的中间位置,以便执行循环中的部分内容,而不是所有内容?
发布于 2012-08-31 06:42:42
可以,您可以将条件和continue插入到您想要的任何位置:
<?php foreach($files as $f): ?>
lots of HTML
<?php if (condition) continue; ?>
more HTML
<?php endforeach; ?>。
发布于 2018-05-10 16:52:27
我有一个非常相似的问题,所有的搜索都把我带到了这里。希望有人觉得我的帖子有用。来自我自己的代码:对于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...
}https://stackoverflow.com/questions/12206604
复制相似问题