PHP Switch and Continue

In this article, we see how to use the switch case statement in PHP. The switch statement is useful to perform different actions based on various conditions.

Read Also: PHP If Else Statement

PHP Switch

The switch statement is like if else if statement which does almost the same thing. It executes one statement from multiple conditions.

Syntax

switch(expression){

    case value1:

        //code to be executed

        break;

    case value2:

        //code to be executed

        break;

    ......

    default:

        //Executes if all cases are not matched;

}

Essential points about switch case in PHP

  • The default is an optional statement.
  • There is only one default in the switch statement.
  • There is only one default in the switch statement. More than one default may lead to error.
  • Each case can have one break statement which terminates the sequence of statement.
  • The break statement is optional to use un switch statement.
  • PHP allows us to use number, character, string, and functions in a switch statement.
  • Nesting of switch statements is allowed, but it makes the program more complex.
  • We can use semicolon(;) instead of colon(:) It will not generate any error.

Example 1

<?php

$favfruit = "Apple";
switch($favfruit){
    case "Apple":
        echo "Your favorite fruit is Apple!";
        break;
    case "Mango":
        echo "Your favorite fruit is Mango!";
        break;
    case "Grapes":
        echo "Your favorite fruit is Grapes!";
        break;
    default:
        echo "Your favorite fruit is neither Apple, Mango, nor Grapes!";
}
?>

Output

Your favorite fruit is Apple

PHP Continue

  • The PHP continue statement is useful to continue the loop.
  • The continue statement continues the current flow of the program and skips the remaining code at the specific condition.
  • It is used within looping and switch control statements when we immediately jump to the next iteration.
  • It is used with all types of loops such as for, while, do-while, and for each loop.
  • The continue statement allows the users to skip the execution of the code for the specified condition.

Syntax

jump-statement; 
continue;

Example

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

Output

1
3
5
7
9

Read More: PHP Loops

Conclusion

When we need to run different blocks of code, the PHP switch statement comes in picture.
I hope you have a great understanding of the switch and continue statement in PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *

More in PHP Tutorial
if else conditional statements in php
PHP if..elseif..else

When we write programs, there will be scenarios where we want to execute a statement only if some conditions satisfied....

Close