Developer
PHP
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP VariablesPHP ConstantsPHP OutputPHP Data TypesPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

PHP Loop Control Structures

In PHP, we have two additional loop control structures. These are used with switch statement too.

The word "loop iteration" is used to specify one round (or one time that the group of code is executed).
  • Break - Ends the execution of the current loop.
  • Continue - Skips the next part of current loop iteration, and jumps to condition checking of the next loop iteration.

PHP Break

break; statement terminates the execution of the current loop.

An optional numeric argument can be used to specify how many loops need to be ended. (break 2; will terminate 2 nested loops)

PHP Break Example


<?php

/*break on 5 */
$a = 0;
while ($a < 10) {
	echo $a . '<br>';
	if ($a === 5) {
		break;
	}
	$a++;
} 

echo '<br>';

/* breaking multiple loops */
for ($a = 0; $a < 10; $a++) {
	echo "$";
	for ($b = 0; $b < 10; $b++) {
		echo "*";
		if ($b === 5) {
			echo '<br> $b is 5. I am exiting';
			break 2;
		}
	}
}

Run Example ››

PHP Continue

continue; skips the next part of the current loop iteration. Then, the next loop iteration will run after checking the conditions.

Like break; statement, continue; also can have a numeric argument to continue multiple loops.

PHP Continue Example


<?php
$a = 0;
while ($a < 10) {
	if ($a === 5) {
		$a++;
		continue; // 5 is not printed
	}
	echo $a . '<br>';
	$a++;
} 

Run Example ››
Advertisement
0
83