PHP continue Statement


Introduction

The continue statement is one of the looping control keywords in PHP. When program flow comes across continue inside a loop, rest of the statements in current iteration of loop are skipped and next iteration of loop starts. It can appear inside while, do while, for as well as foreach loop.

Syntax

while (expr)
{
   ..
   ..
   if (expr1)
   continue;
   ..
   ..
}

In following example, continue statement will be executed every time while loop's counter variable $x is even numbered. As a result odd numbers between 1 to 10 will be printed

Example

 Live Demo

<?php
$x=1;
while ($x<10){
   $x++;
if ($x%2==0)
   continue;
   echo "x = $x" . "
"; } ?>

Output

This will produce following result −

x = 3
x = 5
x = 7
x = 9

The keyword continue can have an optional numeric argument to specify how many levels of inne loops are to be skipped. Default is 1

In following example continue keyword is used with a level argument in inner loop

Example

 Live Demo

<?php
for ($i = 1;$i<=5;$i++) {
   echo "Start Of outer loop
";    for ($j=1;$j<=5;$j++) {       if ($j >3) continue 2;       echo "I : $i J : $j"."
";    }    echo "End of inner loop
"; } ?>

Output

This will produce following result −

Start Of outer loop
I : 1 J : 1
I : 1 J : 2
I : 1 J : 3
Start Of outer loop
I : 2 J : 1
I : 2 J : 2
I : 2 J : 3
Start Of outer loop
I : 3 J : 1
I : 3 J : 2
I : 3 J : 3
Start Of outer loop
I : 4 J : 1
I : 4 J : 2
I : 4 J : 3
Start Of outer loop
I : 5 J : 1
I : 5 J : 2
I : 5 J : 3

Updated on: 19-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements