0

I have been having problems on one of my foreach loops where PART of the loop terminates after just one iteration, with no output or error.

After searching the web for answers, I still don't know any possible causes for this issue (and the code is too large to be useful to the community...)

Therefore my question is, "what are the possible causes for a foreach loop to terminate after just one iteration?" (assuming more iterations are required)

6
  • maybe a break instruction. Commented Jan 13, 2013 at 16:18
  • break, die and return can all cancel a foreach totally, continue can skip the iteration but will not break a loop. Commented Jan 13, 2013 at 16:23
  • "PART of the loop terminates after just one iteration" = One item in the array. Commented Jan 13, 2013 at 16:28
  • @vascowhite (assuming more iterations are required) Commented Jan 13, 2013 at 16:29
  • @Sammaye That assumption may be wrong, many are. Commented Jan 13, 2013 at 16:31

2 Answers 2

0

There are multiple ways to stop a foreach loop. Here are a few examples:

<?php
$range = range(1,10);

// continue;
foreach($range as $r){
    if($r!=1){
        continue;
    }
    echo $r.'<br>';
}

// break;
foreach($range as $r){
    if($r>1){
        break;
    }
    echo $r.'<br>';
}

// die;
foreach($range as $r){
    if($r>1){
        die;
    }
}

Note: continue will not break out of the foreach loop, but can cause data rows to be "skipped"

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

2 Comments

continue won't terminate the loop, but skip to the next index.
yeah, i added that to the bottom.
0

It works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

I think that you should have to follow this link http://php.net/manual/en/control-structures.foreach.php for better knowledge about foreach loop.

1 Comment

If he were experiencing this then the foreach would throw a fatal and would not even go into the first iteration.

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.