Monday 19 April 2021

Php: continue statement

‘continue’ statement skips the current iteration of a loop.

 

Syntax

continue;

 

Example: Printing numbers from 0 to 10, except 2, 3, 5.

for ($i = 0; $i < 10; $i ++) {
    if($i == 2 || $i == 3 || $i == 5){
        continue;
    }
    echo "i = $i\n";
}

 Example 2: Print multiplication table of 2 and 4, and exclude 1, 3, 5, 7 from multiplication.

 

for($i = 2; $i <5; $i++){
    if($i != 2 && $i != 4){
        continue;
    }

    echo "\n\n";

    for($j = 0; $j < 11; $j++){

        if($j == 1 || $j ==3
        || $j == 5 || $j == 7){
            continue;
        }

        $result = $i * $j;
        echo "$i * $j = $result\n";
    }
}

 

Find the below working application.

 

continue_demo.php

#!/usr/bin/php

<?php
echo "Printing numbers from 0 to 10, except 2, 3, 5\n";
for ($i = 0; $i < 10; $i ++) {
    if($i == 2 || $i == 3 || $i == 5){
        continue;
    }
    echo "i = $i\n";
}

echo "\nPrint multiplication table of 2 and 4, and exclude 1, 3, 5, 7 from multiplication\n";
for($i = 2; $i <5; $i++){
    if($i != 2 && $i != 4){
        continue;
    }

    echo "\n\n";

    for($j = 0; $j < 11; $j++){

        if($j == 1 || $j ==3
        || $j == 5 || $j == 7){
            continue;
        }

        $result = $i * $j;
        echo "$i * $j = $result\n";
    }
}
?>

 

Output

$./continue_demo.php 

Printing numbers from 0 to 10, except 2, 3, 5
i = 0
i = 1
i = 4
i = 6
i = 7
i = 8
i = 9

Print multiplication table of 2 and 4, and exclude 1, 3, 5, 7 from multiplication


2 * 0 = 0
2 * 2 = 4
2 * 4 = 8
2 * 6 = 12
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20


4 * 0 = 0
4 * 2 = 8
4 * 4 = 16
4 * 6 = 24
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40

 

‘continue’ statement is available in other form also to skip the iteration of outer loops.

 

Syntax

continue(n): Continue from n loops back.

 

Example

continue(2);

 

Find the below working application.

 

continue_of_n_demo.php

#!/usr/bin/php

<?php
for($i = 1; $i <5; $i++){

    for($j = 0; $j < 5; $j++){

        if($j > $i){
            echo "\n\n";
            continue(2);
        }

        $result = $i * $j;
        echo "$i * $j = $result\n";
    }
    
}
?>

 

Output

$./continue_of_n_demo.php 

1 * 0 = 0
1 * 1 = 1


2 * 0 = 0
2 * 1 = 2
2 * 2 = 4


3 * 0 = 0
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9


4 * 0 = 0
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16

 

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment