2

I'm using a php foreach statement like this:

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

lots of HTML

<?php endforeach; ?>

how can I put a conditional inside the loop that so that it will skip ahead to the next iteration. I know that I'm supposed to use continue, but I'm not sure how to do it with closed php statements like this. Would it be a separate php statement? Could it be placed halfway down in the HTML so that some but not all of the stuff within the loop is executed?

2
  • Well, in between. Where you need it. Commented Aug 30, 2012 at 22:42
  • Can you please clarify your question? and some code ? Commented Aug 30, 2012 at 22:42

2 Answers 2

4

Yes, you can insert the condition and continue wherever you want:

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

lots of HTML

<?php if (condition) continue; ?>

more HTML

<?php endforeach; ?>

See it in action.

Sign up to request clarification or add additional context in comments.

Comments

0

I had a very similar problem and all searches led me here. Hope somebody finds my post useful. From my own code: For PHP 5.3.0 this worked:

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...
}

For PHP 7.0.19 the following worked:

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...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.