PHP Switch and Continue

The switch statement is used to perform different actions based on different conditions. In this article, we will 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. It executes one block of code from many, based on the given 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. More than one default may lead to error.
  • Each case can have one break statement which terminates the sequence of the statement.
  • The break statement is optional to use in a 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 the 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 based on different conditions, the PHP switch statement comes into the picture.

You can refer to our previous blog on if..else..elseif statements to understand the differences between switch cases and the other conditional statements. We have also posted other blogs on the other basic concepts of PHP. Stay motivated and Happy Learning!

Leave a Reply

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