PHP continue statement

The PHP continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.

The continue statement is used within looping and switch control structure when you immediately jump to the next iteration.

The continue statement can be used with all types of loops such as – for, while, do-while, and foreach loop. The continue statement allows the user to skip the execution of the code for the specified condition.

Syntax

The syntax for the continue statement is given below:

  1. jump-statement;  
  2. continue;  

Flowchart:

PHP continue statement

PHP Continue Example with for loop

Example

In the following example, we will print only those values of i and j that are same and skip others.

<?php  
    //outer loop  
    for ($i =1; $i<=3; $i++) {  
        //inner loop  
        for ($j=1; $j<=3; $j++) {  
            if (!($i == $j) ) {  
                continue;       //skip when i and j does not have same values  
            }  
            echo $i.$j;  
            echo "</br>";  
        }  
    }  
?>  

Output:

11
22 
33

PHP continue Example in while loop

Example

In the following example, we will print the even numbers between 1 to 20.

<?php  
    //php program to demonstrate the use of continue statement  
  
    echo "Even numbers between 1 to 20: </br>";  
    $i = 1;  
    while ($i<=20) {  
        if ($i %2 == 1) {  
            $i++;  
            continue;   //here it will skip rest of statements  
        }  
        echo $i;  
        echo "</br>";  
        $i++;  
    }     
?>  

Output:

Even numbers between 1 to 20: 
2
4
6
8
10
12
14
16
18
20

PHP continue Example with array of string

Example

The following example prints the value of array elements except those for which the specified condition is true and continue statement is used.

<?php  
    $number = array ("One", "Two", "Three", "Stop", "Four");  
    foreach ($number as $element) {  
        if ($element == "Stop") {  
            continue;  
        }  
        echo "$element </br>";  
    }  
?>  

Output:

One 
Two 
Three
Four

PHP continue Example with optional argument

The continue statement accepts an optional numeric value, which is used accordingly. The numeric value describes how many nested structures it will exit.

Example

Look at the below example to understand it better:

<?php  
    //outer loop  
    for ($i =1; $i<=3; $i++) {  
        //inner loop  
        for ($j=1; $j<=3; $j++) {  
            if (($i == $j) ) {      //skip when i and j have same values  
                continue 1;     //exit only from inner for loop   
            }  
            echo $i.$j;  
            echo "</br>";  
        }  
    }     
?>  

Output:

12
13
21 
23
31
32 

PHP Break

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only.

The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow of the program at the specified condition and program control resumes at the next statements outside the loop.

The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and also with switch case.

Syntax

  1. jump statement;  
  2. break;  

PHP Break: inside loop

Let’s see a simple example to break the execution of for loop if value of i is equal to 5.

<?php    
for($i=1;$i<=10;$i++){    
echo "$i <br/>";    
if($i==5){    
break;    
}    
}    
?>  

Output:

1
2
3
4
5

PHP Break: inside inner loop

The PHP break statement breaks the execution of inner loop only.

<?php    
for($i=1;$i<=3;$i++){    
 for($j=1;$j<=3;$j++){    
  echo "$i   $j<br/>";    
  if($i==2 && $j==2){    
   break;    
  }    
 }    
}    
?>  

Output:

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

PHP Break: inside switch statement

The PHP break statement breaks the flow of switch case also.

<?php        
$num=200;        
switch($num){        
case 100:        
echo("number is equals to 100");        
break;        
case 200:        
echo("number is equal to 200");        
break;        
case 50:        
echo("number is equal to 300");        
break;        
default:        
echo("number is not equal to 100, 200 or 500");        
}       
?>  

Output:

number is equal to 200

PHP Break: with array of string

<?php  
//declare an array of string  
$number = array ("One", "Two", "Three", "Stop", "Four");  
foreach ($number as $element) {  
if ($element == "Stop") {  
break;  
}  
echo "$element </br>";  
}  
?>  

Output:

One 
Two 
Three

You can see in the above output, after getting the specified condition true, break statement immediately ends the loop and control is came out from the loop.

PHP Break: switch statement without break

It is not essential to break out of all cases of a switch statement. But if you want that only one case to be executed, you have to use break statement.

<?php  
$car = 'Mercedes Benz';  
switch ($car) {    
default:  
echo '$car is not Mercedes Benz<br>';  
case 'Orange':  
echo '$car is Mercedes Benz';  
}  
?>  

Output:

$car is not Mercedes Benz
$car is Mercedes Benz

PHP Break: using optional argument

The break accepts an optional numeric argument, which describes how many nested structures it will exit. The default value is 1, which immediately exits from the enclosing structure.

<?php  
$i = 0;  
while (++$i) {  
    switch ($i) {  
        case 5:  
            echo "At matched condition i = 5<br />\n";  
            break 1;  // Exit only from the switch.   
       case 10:  
            echo "At matched condition i = 10; quitting<br />\n";  
            break 2;  // Exit from the switch and the while.   
       default:  
            break;  
    }  
}?>  

Output:

At matched condition i = 5
At matched condition i = 10; quitting

PHP do-while loop

PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.

The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the loop at least once and the number of iterations is not even fixed, it is recommended to use the do-while loop.

It executes the code at least one time always because the condition is checked after executing the code.

The do-while loop is very much similar to the while loop except the condition check. The main difference between both loops is that while loop checks the condition at the beginning, whereas do-while loop checks the condition at the end of the loop.

Syntax

do{  
//code to be executed  
}while(condition); 

Flowchart

flowchart of php do while loop

Example

<?php    
$n=1;    
do{    
echo "$n<br/>";    
$n++;    
}while($n<=10);    
?>    

Output:

1
2
3
4
5
6
7
8
9
10

Example

A semicolon is used to terminate the do-while loop. If you don’t use a semicolon after the do-while loop, it is must that the program should not contain any other statements after the do-while loop. In this case, it will not generate any error.

 <?php  
    $x = 5;  
    do {  
        echo "Welcome to protutorials! </br>";  
        $x++;  
    } while ($x < 10);  
?>  

Output:

Welcome to protutorials!
Welcome to protutorials!
Welcome to protutorials!
Welcome to protutorials!
Welcome to protutorials!

Example

The following example will increment the value of $x at least once. Because the given condition is false.

 <?php  
    $x = 1;  
    do {  
        echo "1 is not greater than 10.";  
        echo "</br>";  
        $x++;  
    } while ($x > 10);  
    echo $x;  
?>

Output:

1 is not greater than 10.
2

Difference between while and do-while loop

while Loopdo-while loop
The while loop is also named as entry control loop.The do-while loop is also named as exit control loop.
The body of the loop does not execute if the condition is false.The body of the loop executes at least once, even if the condition is false.
Condition checks first, and then block of statements executes.Block of statements executes first and then condition checks.
This loop does not use a semicolon to terminate the loop.Do-while loop use semicolon to terminate the loop.

PHP foreach loop

The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype.

The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.

In foreach loop, we don’t need to increment the value.

Syntax

foreach ($array as $value) {  
    //code to be executed  
}  

There is one more syntax of foreach loop.

Syntax

foreach ($array as $key => $element) {   
    //code to be executed  
}  

Flowchart

php for loop flowchart

Example 1:

PHP program to print array elements using foreach loop.

<?php  
    //declare array  
    $season = array ("Summer", "Winter", "Autumn", "Rainy");  
      
    //access array elements using foreach loop  
    foreach ($season as $element) {  
        echo "$element";  
        echo "</br>";  
    }  
?>

Output:

Summer 
Winter 
Autumn 
Rainy

Example 2:

PHP program to print associative array elements using foreach loop.

<?php  
    //declare array  
    $employee = array (  
        "Name" => "Alex",  
        "Email" => "alex_jtp@gmail.com",  
        "Age" => 21,  
        "Gender" => "Male"  
    );  
      
    //display associative array element through foreach loop  
    foreach ($employee as $key => $element) {  
        echo $key . " : " . $element;  
        echo "</br>";   
    }  
?> 

Output:

Name : Alex
Email : alex_jtp@gmail.com
Age : 21
Gender : Male

Example 3:

Multi-dimensional array

<?php  
    //declare multi-dimensional array  
    $a = array();  
    $a[0][0] = "Alex";  
    $a[0][1] = "Bob";  
    $a[1][0] = "Camila";  
    $a[1][1] = "Denial";  
      
    //display multi-dimensional array elements through foreach loop  
    foreach ($a as $e1) {  
        foreach ($e1 as $e2) {  
            echo "$e2\n";  
        }  
    }  
?>  

Output:

Alex Bob Camila Denial

Example 4:

Dynamic array

<?php  
    //dynamic array  
    foreach (array ('p', 'r', 'o', 't', 'u', 't', 'o', 'r', 'i', 'a','l','s') as $elements) {  
        echo "$elements\n";  
    }  
?> 

Output:

p r o t u t o r i a l s

PHP Switch

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

Syntax

switch(expression){      
case value1:      
 //code to be executed  
 break;  
case value2:      
 //code to be executed  
 break;  
......      
default:       
 code to be executed if all cases are not matched;    
}  

Important points to be noticed about switch case:

  1. The default is an optional statement. Even it is not important, that default must always be the last statement.
  2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
  3. Each case can have a break statement, which is used to terminate the sequence of statement.
  4. The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
  5. PHP allows you to use number, character, string, as well as functions in switch expression.
  6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
  7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP Switch Example

<?php      
$num=20;      
switch($num){      
case 10:      
echo("number is equals to 10");      
break;      
case 20:      
echo("number is equal to 20");      
break;      
case 30:      
echo("number is equal to 30");      
break;      
default:      
echo("number is not equal to 10, 20 or 30");      
}     
?>  

Output:

number is equal to 20

PHP switch statement with character

Program to check Vowel and consonant

We will pass a character in switch expression to check whether it is vowel or constant. If the passed character is A, E, I, O, or U, it will be vowel otherwise consonant.

<?php      
    $ch = 'U';  
    switch ($ch)  
    {     
        case 'a':   
            echo "Given character is vowel";  
            break;  
        case 'e':   
            echo "Given character is vowel";  
            break;  
        case 'i':   
            echo "Given character is vowel";  
            break;  
        case 'o':   
            echo "Given character is vowel";  
            break;    
        case 'u':   
            echo "Given character is vowel";  
            break;  
        case 'A':   
            echo "Given character is vowel";  
            break;  
        case 'E':   
            echo "Given character is vowel";  
            break;  
        case 'I':   
            echo "Given character is vowel";  
            break;  
        case 'O':   
            echo "Given character is vowel";  
            break;  
        case 'U':   
            echo "Given character is vowel";  
            break;  
        default:   
            echo "Given character is consonant";  
            break;  
    }  
?>  

Output:

Given character is vowel

PHP switch statement with String

PHP allows to pass string in switch expression. Let’s see the below example of course duration by passing string in switch case statement.

<?php      
    $ch = "B.Tech";  
    switch ($ch)  
    {     
        case "BCA":   
            echo "BCA is 3 years course";  
            break;  
        case "Bsc":   
            echo "Bsc is 3 years course";  
            break;  
        case "B.Tech":   
            echo "B.Tech is 4 years course";  
            break;  
        case "B.Arch":   
            echo "B.Arch is 5 years course";  
            break;  
        default:   
            echo "Wrong Choice";  
            break;  
    }  
?>

Output:

B.Tech is 4 years course

PHP switch statement is fall-through

PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if break statement is not found.

<?php      
    $ch = 'c';  
    switch ($ch)  
    {     
        case 'a':   
            echo "Choice a";  
            break;  
        case 'b':   
            echo "Choice b";  
            break;  
        case 'c':   
            echo "Choice c";      
            echo "</br>";  
        case 'd':   
            echo "Choice d";  
            echo "</br>";  
        default:   
            echo "case a, b, c, and d is not found";  
    }  
?>  

Output:

Choice c
Choice d
case a, b, c, and d is not found

PHP nested switch statement

Nested switch statement means switch statement inside another switch statement. Sometimes it leads to confusion.

<?php      
    $car = "Hyundai";                   
        $model = "Tucson";    
        switch( $car )    
        {    
            case "Honda":    
                switch( $model )     
                {    
                    case "Amaze":    
                           echo "Honda Amaze price is 5.93 - 9.79 Lakh.";   
                        break;    
                    case "City":    
                           echo "Honda City price is 9.91 - 14.31 Lakh.";    
                        break;     
                }    
                break;    
            case "Renault":    
                switch( $model )     
                {    
                    case "Duster":    
                        echo "Renault Duster price is 9.15 - 14.83 L.";  
                        break;    
                    case "Kwid":    
                           echo "Renault Kwid price is 3.15 - 5.44 L.";  
                        break;    
                }    
                break;    
            case "Hyundai":    
                switch( $model )     
                {    
                    case "Creta":    
                        echo "Hyundai Creta price is 11.42 - 18.73 L.";  
                        break;    
        case "Tucson":    
                           echo "Hyundai Tucson price is 22.39 - 32.07 L.";  
                        break;   
                    case "Xcent":    
                           echo "Hyundai Xcent price is 6.5 - 10.05 L.";  
                        break;    
                }    
                break;     
        }  
?> 

Output:

Hyundai Tucson price is 22.39 - 32.07 L.