0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP Switch Statement: Syntax and Use Cases

Posted at

PHP_Tutorial.jpg

Introduction

In PHP, the switch statement is an important part of the decision-making statement that helps to manage the different actions depending on multiple conditions. It works similarly to multiple if...else if statements but provides cleaner, more readable code when dealing with numerous possible conditions.

The switch statement is particularly useful when you need to compare a single value against several potential matches, such as menu selections, user roles, or days of the week.

In this blog, we will explore the PHP switch statement with syntax and practical use cases up to the advanced level.

Switch Statement

This statement allows you to execute multiple if-else conditions in a single variable. If the number of conditions is excessive, you can use the switch statement.

Syntax:

<?php
switch (expression) {
    case data1:
        // Write your code here if the first condition is fulfilled
        break;
    case data 2:
        // Write your code here if the first condition is fulfilled
        break;
    // Write your code here if you use multiple use cases
    default:
        // Write your code here if all the conditions are not executed
        break;
}
?>

Example

Code:

<?php
$marks = 85;
echo "Student Grading System\n";
echo "Marks Obtained: $marks\n";

switch (true) {
    case ($marks >= 90 && $marks <= 100):
        echo "Grade: A+ (Excellent)\n";
        break;
    case ($marks >= 80 && $marks < 90):
        echo "Grade: A (Very Good)\n";
        break;
    case ($marks >= 70 && $marks < 80):
        echo "Grade: B (Good)\n";
        break;
    case ($marks >= 60 && $marks < 70):
        echo "Grade: C (Average)\n";
        break;
    case ($marks >= 50 && $marks < 60):
        echo "Grade: D (Pass)\n";
        break;
    case ($marks < 50):
        echo "Grade: F (Fail)\n";
        break;
    default:
        echo "Invalid Marks!\n";
}
?>

Output:

Student Grading System
Marks Obtained: 85
Grade: A (Very Good)

Without Break Statement:

If you are not using the break statement in a switch statement, it will continue to run all the cases without matching the test cases. This process is known as the fall-through.

Syntax:

switch (expression) {
    case value1:
        // Code to be executed if expression == value1
        // No break here, so execution will continue to the next case
    case value2:
        // Code to be executed if expression == value2
        // No break here, so the next case will also execute

    case value3:
        // Code to be executed if expression == value3        
    default:
        // Code to be executed if no case matches
}

Example

Code:

<?php
$day = "Tuesday";
echo "Day Calculator (Without break)\n";
echo "Day Entered: $day\n";

switch ($day) {
    case "Monday":
        echo "Start of the week\n";
    case "Tuesday":
        echo "Second day of the week\n";
    case "Wednesday":
        echo "Midweek day\n";
    case "Thursday":
        echo "Almost Friday\n";
    case "Friday":
        echo "End of the workweek industry\n";
    case "Saturday":
    case "Sunday":
        echo "It's the weekend to enjoy!\n";
    default:
        echo "Invalid day entered\n";
}
?>

Output:

Day Calculator (Without break)
Day Entered: Tuesday
Second day of the week
Midweek day
Almost Friday
End of the workweek industry
It's the weekend to enjoy!
Invalid day entered

Using the break keyword:

Using the break, the switch statement automatically breaks the block and also stops the execution of your code. The default block does not contain a break; it will execute if all the cases are not matched.

Example

Code:

<?php
$num1 = 12;
$num2 = 4;
$ope = "*";
switch ($ope) {
    case "+":
        echo "Addition of two numbers: " . ($num1 + $num2) . "\n";
        break;
    case "-":
        echo "Subtraction of two numbers: " . ($num1 - $num2) . "\n";
        break;
    case "*":
        echo "Multiply of two numbers: " . ($num1 * $num2) . "\n";
        break;
    case "/":
        if ($num2 != 0) {
            echo "Division: " . ($num1 / $num2) . "\n";
        } else {
            echo "Cannot divide by zero\n";
        }
        break;

    default:
        echo "Invalid user input\n";
}
?>

Output:

Multiply of two numbers: 48

Using the default keyword:

This keyword is executed when all the cases are not matched.

Example

Code:

<?php
$signal = "Blue";

switch ($signal) {
    case "Red":
        echo "Stop the vehicle!\n";
        break;
    case "Yellow":
        echo "Get ready to move!\n";
        break;
    case "Green":
        echo "Go!\n";
        break;
    default:
        echo "Invalid signal! Please enter Red, Yellow, or Green.\n";
}
?>

Output:

Invalid signal! Please enter Red, Yellow, or Green.

Nested Switch Statement:

A nested switch statement in PHP refers to using one switch statement inside another. This structure is useful when you need to make decisions based on multiple levels of conditions.

Example

Code:

<?php
$country = "USA";
$city = "New York";
switch ($country) {
    case "USA":
        switch ($city) {
            case "New York":
                echo "New York is the Big City!";
                break;
            case "Los Angeles":
                echo "Los Angeles is famous for Hollywood!";
                break;
            default:
                echo "Unknown city in USA.";
        }
        break;

    case "India":
        switch ($city) {
            case "Delhi":
                echo "Delhi is the capital of India!";
                break;
            case "Mumbai":
                echo "Mumbai is the city of dreams!";
                break;
            default:
                echo "Unknown city in India.";
        }
        break;

    default:
        echo "Unknown country.";
}
?>

Output:

New York is the Big City!

Practical use case of Switch Statement

1) Menu Choice program:

Code:

<?php
$choice = 3;

switch ($choice) {
    case 1:
        echo "You selected Coffee.";
        break;
    case 2:
        echo "You selected Tea.";
        break;
    case 3:
        echo "You selected Juice.";
        break;
    default:
        echo "Invalid selection!";
}
?>

Output:

You selected Juice.

2) HTTP Status Code Method:

Code:

<?php
$statusCode = 404;

switch ($statusCode) {
    case 200:
        echo "200 OK - Request successful.";
        break;
    case 404:
        echo "404 Not Found - The page could not be found.";
        break;
    case 500:
        echo "500 Internal Server Error - Server problem.";
        break;
    default:
        echo "Unknown status code.";
}
?>

Output:

404 Not Found - The page could not be found.

Conclusion:

I hope this blog gives a clear overview of the PHP switch statement with practical use cases and syntax from beginner to professional-level developers. This statement is generally used for control structures to manage multiple cases easily. It gives a more readable and cleaner way to run on different values in a single variable.

Tpoint Tech gives you complete PHP tutorials with deeply explanations, real-life examples, a PHP online compiler, and generally asked interview questions to upgrade your skills.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?