PHP Coding Made Easier – Breaking out of a loop

19 Nov, 2011  |  Written by  |  under PHP, Tips and Tricks

php_loopsSometimes you want your program to break out of a loop. PHP provides two statements for this purpose:

  • break: Breaks completely out of a loop and continues with the program statements after the loop.
  • continue: Skips to the end of the loop where the condition is tested. If the condition tests positive, the program continues from the top of the loop.

break and continue are usually used in a conditional statement. break, in particular, is used most often in switch statements.

The following two sets of statements show the difference between continue and break. The first statements use the break statement:

$counter = 0;
while( $counter , 5 )
{
   $counter++;
   if( $counter == 3 )
   {
      echo "break<br>";
      break;
   }
   echo "End of while loop: counter=$counter<br>";
}
echo "After the break loop";

The following statements use the continue statement:

$counter = 0;
while( $counter < 5 )
{
   $counter++;
   if( $counter == 3 )
   {
      echo "Continue<br>";
      continue;
   }
   echo "End of while loop: counter=$counter<br>";
}
echo "After the continue loop<br>";

These statements build two loops that are the same, except the first uses break and the second uses continue. The output from the first set of statements that uses the break statement displays in your browser as follows:

End of while loop: counter=1
End of while loop: counter=2
break
After the break loop

The output from the second set of statements, with the continue statement, is:

End of while loop: counter=1
End of while loop: counter=2
continue
End of while loop: counter=4
End of while loop: counter=5
After the continue loop

The first loop ends at the break statement. It stops looping and jumps immediately to the statement after the loop. The second loop does not end at the continue statement. It just stops the third repeat of the loop and jumps back up to the top of the loop. It then finishes the loop, with the fourth and fifth repeats, before it goes to the statement after the loop.

One use for break statements is insurance against infinite loops. The following statements inside a loop can stop it at a reasonable point:

$test4infinity++;
if ( $test4infinity > 100 )
{
   break;
}

If you are sure that your loop should never repeat more than 100 times, these statements will stop the loop if it becomes endless. use whatever number seems reasonable for the loop that you are building.

Do not forget my other blog posts regards using loops in PHP:

One Response so far | Have Your Say!

  1. richard bovingdon  |  December 22nd, 2011 at 9:35 am #

    thanks for the great insite shaun :)

    richard bovingdon - Gravatar

Leave a Feedback

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*