0
0
PHPprogramming~5 mins

Switch statement execution in PHP

Choose your learning style9 modes available
Introduction

A switch statement helps you choose one action from many options based on a value. It makes your code easier to read than many if-else checks.

You want to run different code depending on a user's choice from a menu.
You need to handle different commands or inputs in a program.
You want to replace multiple if-else statements that check the same variable.
You want clear and organized code when checking many possible values.
Syntax
PHP
switch (expression) {
    case value1:
        // code to run if expression == value1
        break;
    case value2:
        // code to run if expression == value2
        break;
    default:
        // code to run if no case matches
        break;
}

The break stops the switch from running the next cases.

The default case runs if no other case matches.

Examples
This example prints a message based on the day stored in $day.
PHP
switch ($day) {
    case 'Monday':
        echo "Start of the week";
        break;
    case 'Friday':
        echo "Almost weekend";
        break;
    default:
        echo "Just another day";
        break;
}
Multiple cases (1, 2, 3) run the same code for small numbers.
PHP
switch ($number) {
    case 1:
    case 2:
    case 3:
        echo "Small number";
        break;
    default:
        echo "Other number";
        break;
}
Sample Program

This program checks the color and prints the matching traffic signal message.

PHP
<?php
$color = 'green';
switch ($color) {
    case 'red':
        echo "Stop";
        break;
    case 'yellow':
        echo "Get ready";
        break;
    case 'green':
        echo "Go";
        break;
    default:
        echo "Unknown color";
        break;
}
?>
OutputSuccess
Important Notes

Always use break to avoid running code in the next cases unintentionally.

The default case is optional but useful for unexpected values.

Switch works best when checking one variable against many fixed values.

Summary

Switch statements let you pick code to run based on a value.

Use case for each option and break to stop.

default runs if no cases match.