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.

JavaScript Switch case

JavaScript Switch case is used to execute a block of statement out of multiple blocks of statements based on a condition. JavaScript switch is a condition-based statement that has multiple conditions but executes only one block at a time.

In switch statement, the switch expression is evaluated only once and then the output is compared with every case mentioned inside the switch block and if the output of expression matches one of the cases then the statement written inside the block of that case is executed. If no case matches then the default case is executed.

JavaScript switch case is used in applications where you have to implement a menu like system in which based on user input certain action is taken.

JavaScript switch: Syntax

The expression which evaluates the condition is written inside the switch(expression), followed by a curly bracket which creates a switch block in which the different cases are defined.

switch(expression)
{
case 1:
    //code
    break;
case 2:
    //code
    break;
default:
}

Based on the value of the expression’s output, one of the many cases gets executed, and then the break statement is called which breaks the execution, and the switch case gets exited.

NOTE: If we do not add the break statement after the code statements in the switch case block, then the interpreter would execute each and every case after the matched case.

JavaScript Switch case: Example

In this example, we are using the switch case and each case executes based on the provided value.

let a = 1; switch (a) { case 1: alert(‘case 1 has been executed’); break; case 2: alert(“case 2 has been executed”); break; case 3: alert(“case 3 has been executed”); break; case 4: alert(“case 4 has been executed”); break; default: alert(“default case executed”); }

In the above example, we have used the break statement to terminate the switch case.

JavaScript Switch Case Example without break

Use of the break statement is optional, if we don’t use it then the switch case does not terminate and executes all the rest of the cases till the end, after the matched case. See the below example:

JavaScript Switch Case Example

Switch Case Example

let a = 2; switch (a) { case 1: alert(‘case 1 has been executed’); case 2: alert(“case 2 has been executed”); case 3: alert(“case 3 has been executed”); case 4: alert(“case 4 has been executed”); default: alert(“default case executed”); }

JavaScript Switch Case Default

The default statement is executed if the switch expression output does not match with any of the given cases.

Switch Default Case Example

    <script>
        let a = 6;
        switch (a)
        {
            case 1: alert('case 1 has been executed');
            case 2:
                alert("case 2 has been executed");
            case 3:
                alert("case 3 has been executed");
            case 4:
                alert("case 4 has been executed");
            default:
                alert("default case executed, no matched case is found");
        }
    </script>
</body>

With this, we have covered the JavaScript switch statement. Although if else statements are popular and used in most of the cases, in some scenarios having using switch statement makes the code more readable and scalable. So choose wisely, what to use when.

C++ switch..case Statement

In this tutorial, we will learn about switch statement and its working in C++ programming with the help of some examples.

The switch statement allows us to execute a block of code among many alternatives.

The syntax of the switch statement in C++ is:

switch (expression)  {
    case constant1:
        // code to be executed if 
        // expression is equal to constant1;
        break;

    case constant2:
        // code to be executed if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if
        // expression doesn't match any constant
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label.

  • If there is a match, the corresponding code after the matching label is executed. For example, if the value of the variable is equal to constant2, the code after case constant2: is executed until the break statement is encountered.
  • If there is no match, the code after default: is executed.

Note: We can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is cleaner and much easier to read and write.


Flowchart of switch Statement

C++ switch...case flowchart
Flowchart of C++ switch…case statement

Example: Create a Calculator using the switch Statement

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> num1 >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            cout << num1 << " / " << num2 << " = " << num1 / num2;
            break;
        default:
            // operator is doesn't match any case constant (+, -, *, /)
            cout << "Error! The operator is not correct";
            break;
    }

    return 0;
}

Run Code

Output 1

Enter an operator (+, -, *, /): +
Enter two numbers: 
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -
Enter two numbers: 
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *
Enter two numbers: 
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /
Enter two numbers: 
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?
Enter two numbers: 
2.3
4.5
Error! The operator is not correct.

In the above program, we are using the switch...case statement to perform addition, subtraction, multiplication, and division.

How This Program Works

Notice that the break statement is used inside each case block. This terminates the switch statement.

If the break statement is not used, all cases after the correct case are executed.

  1. We first prompt the user to enter the desired operator. This input is then stored in the char variable named oper.
  2. We then prompt the user to enter two numbers, which are stored in the float variables num1 and num2.
  3. The switch statement is then used to check the operator entered by the user:
    • If the user enters +, addition is performed on the numbers.
    • If the user enters -, subtraction is performed on the numbers.
    • If the user enters *, multiplication is performed on the numbers.
    • If the user enters /, division is performed on the numbers.
    • If the user enters any other character, the default code is printed.

C# Loop control statements

Break

The C# break is used to break loop or switch statement. It breaks the current flow of the program at the given condition. In case of inner loop, it breaks only inner loop.

C# Break Statement Example

using System;
public class BreakExample
{
public static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
Output:
1
2
3
4

Continue

The C# continue statement is used to continue loop. It continues the current flow of the program and skips the remaining code at specified condition. In case of inner loop, it continues only inner loop.

C# Continue Statement Example

using System;
public class ContinueExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
Console.WriteLine(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10

Goto

The C# goto statement is also known jump statement. It is used to transfer control to the other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

Currently, it is avoided to use goto statement in C# because it makes the program complex.

C# Goto Statement Example

using System;
public class GotoExample
{
public static void Main(string[] args)
{
ineligible:
Console.WriteLine(“You are not eligible to vote!”);

Console.WriteLine(“Enter your age:\n”);
int age = Convert.ToInt32(Console.ReadLine());
if (age < 18)
{
goto ineligible;
}
else
{
Console.WriteLine(“You are eligible to vote!”);
}
}
}
output:
You are not eligible to vote!
Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!