首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在PHP foreach循环中使用条件

在PHP foreach循环中使用条件
EN

Stack Overflow用户
提问于 2012-08-31 06:39:59
回答 2查看 2.4K关注 0票数 1

我使用的php foreach语句如下:

代码语言:javascript
复制
<?php foreach($files as $f): ?>

大量的HTML

代码语言:javascript
复制
<?php endforeach; ?>

我怎样才能把一个条件放在循环里面,这样它就会跳到下一个迭代。我知道我应该使用continue,但我不确定如何使用像这样的封闭php语句。这会是一个单独的php声明吗?是否可以将它放在HTML的中间位置,以便执行循环中的部分内容,而不是所有内容?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-31 06:42:42

可以,您可以将条件和continue插入到您想要的任何位置:

代码语言:javascript
复制
<?php foreach($files as $f): ?>

lots of HTML

<?php if (condition) continue; ?>

more HTML

<?php endforeach; ?>

票数 3
EN

Stack Overflow用户

发布于 2018-05-10 16:52:27

我有一个非常相似的问题,所有的搜索都把我带到了这里。希望有人觉得我的帖子有用。来自我自己的代码:对于PHP 5.3.0,这是可行的:

代码语言:javascript
复制
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,可以执行以下操作:

代码语言:javascript
复制
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...
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12206604

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档