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
Further Reading
Examples of Array Functions in PHP
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML