The following code shows an Example of switch case statement in PHP.

Basically, the following example accepts the user input using an HTML form. Further, the user needs to provide the name of a color as input. When user clicks on the submit button, the PHP file switchcase.php executes. The following code shows the file myform.php.

myform.php

<form name="f1" method="POST" action="switchcase.php">
 Enter a Color: <input type="text" name="t1"/>
 <br/>
 <input type="submit" value="Submit"/>
</form>

switchcase.php

In fact, the user input is transferred using the POST method. So, the POST variable retrieves it and trims it to remove extra spaces. After that, a specific case statement executes.

<body id="b1">
<?php
echo '<h1>Example of using switch case Statement in PHP</h1>';
$colorname=$_POST['t1'];
$colorname=trim($colorname);

switch($colorname)
{
    case 'Red': echo '<script>document.getElementById("b1").style.color="Red";</script>';break;
    case 'Blue': echo '<script>document.getElementById("b1").style.color="Blue";</script>';break;
    case "Orange": echo '<script>document.getElementById("b1").style.color="Orange";</script>';break;
    case 'Green': echo '<script>document.getElementById("b1").style.color="Green";</script>';break;
    case 'Purple': echo '<script>document.getElementById("b1").style.color="Purple";</script>';break;
    case 'Yellow': echo '<script>document.getElementById("b1").style.color="Yellow";</script>';break;
    default: echo '<script>document.getElementById("b1").style.color="Pink";</script>';break;
}

?>
</body>

Output

A Form to Accept User Input
A Form to Accept User Input
The Output of the Example of switch case statement in PHP
The Output of the Example of switch case statement in PHP

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

PHP Practice Questions