Continue Statement in PHP

Continue Statement in PHP

  • PHP
  • 3 mins read

In this tutorial, you will learn how to use Continue Statement in PHP.

What is Continue Statement in PHP?

It is a statement which can use inside a loop, and when the continue statement encounters, then the loop control jumps to the beginning of that loop for next iteration and skip the execution of loop body statements for the current iteration.

Now we will write a program for implementing a continue statement:

In this program, we are using a for loop, and inside this loop, we are taking a condition with a continue statement.

<html>
    <body>
        <?php
for($i=1;$i<=5;$i=$i+1)
{
    if($i>2)
    {
        continue;
    }
    echo "We know that"."<br>";
}
        ?>
    </body>
</html>

Output

We know that
We know that

Here loop is running from 1 to 5 and loop body statement here echo "We know that"."<br>"; is skipping its execution when the value of loop variable is greater than 2 and loop control is jumping to the beginning of the loop for next iteration.

There is a program, which is containing a for loop and inside this loop, there is a condition here $i>1. For the satisfaction of that condition, loop body statement(here $sum=$sum+$i) is skipping it's execution with a continue statement.

<html>
    <body>
        <?php
$sum=0;
for($i=1;$i<=5;$i=$i+1)
{
    if($i>1)
    {
        continue;
    }
    $sum=$sum+$i;
}
echo "The total value of sum is=".$sum;
        ?>
    </body>
</html>

Output

The total value of sum is=1

Here loop is running from 1 to 5 and $sum=$sum+$i is executing for only one time because based on the condition of $i>1 with a continue statement inside the loop body.

Now we are writing another program for implementing the continue statement:

In this program, we are using an array here $a with three string elements and a function f1. Inside the function, there is a loop and we are trying to display the value of string element of the array if the array element value does not start with a vowel.

<html>
    <body>
        <?php
$a=array("ajay","babu","amit");//global variable
function f1()
{
    global $a; //accessing global variable inside the function body
    for($i=0;$i<count($a);$i=$i+1)
    {
        $b=substr($a[$i],0,1); //extraction first letter of each array element
        if($b=="a"||$b=="e"||$b=="i"||$b=="o"||$b=="u")
        {
            continue;
        }
        echo $a[$i]."<br>";
    }
}
f1(); //function calling
        ?>
    </body>
</html>

Output

babu

Here the first and third array element value starts with a vowel. So only "babu" is displaying. Because the for first and third array element if the condition is satisfying and so loop body statement(here echo $a[$i]."<br>")is skipping its execution after calling the function.