Introduction:
Explore the power of the PHP switch statement with our in-depth tutorial. Learn how to efficiently handle multiple conditions, streamline code, and make your PHP scripts more readable. Dive into practical examples and enhance your web development skills.
The switch statement in PHP is used to select one of many blocks of code to be executed. It is an alternative to a series of if statements.
The basic syntax of the switch statement looks like this:
switch (expression) { case label1: // code to be executed if expression matches label1 break; case label2: // code to be executed if expression matches label2 break; // more cases as needed default: // code to be executed if none of the cases match the expression }
Explanation:
Here’s a breakdown of the components:
expression: This is the value that you want to compare. The switch statement evaluates this expression once and then compares it with the values in the case labels.
case label1, case label2, etc.: These are the different cases or values that you want to compare with the expression. If the expression matches a case value, the corresponding block of code is executed.
break: This keyword is used to exit the switch statement. After a matching case is found and its code block is executed, the break statement is used to terminate the switch statement. If you omit the break, execution will “fall through” to the next case.
default: This is an optional case that is executed if none of the cases match the expression.
Here’s an example:
$day = "Monday"; switch ($day) { case "Monday": echo "It's the start of the week."; break; case "Friday": echo "TGIF!"; break; default: echo "It's a regular day."; }
In this example, if $day is “Monday,” it will output “It’s the start of the week.” If $day is “Friday,” it will output “TGIF!” If neither, it will output “It’s a regular day.”
complete example in html with explanation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Day of the Week Greeting</title> </head> <body> <h1>Day of the Week Greeting</h1> <form method="post" action="greet.php"> <label for="day">Select a day:</label> <select name="day" id="day"> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> <option value="Friday">Friday</option> <option value="Saturday">Saturday</option> <option value="Sunday">Sunday</option> </select> <button type="submit">Get Greeting</button> </form> </body> </html>
Explanation:
Now, let’s create the “greet.php” file with the PHP code that uses the switch statement to provide a greeting based on the selected day.
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if the form is submitted using POST method // Retrieve the selected day from the form $selectedDay = $_POST["day"]; // Use a switch statement to provide a greeting based on the selected day switch ($selectedDay) { case "Monday": $greeting = "It's the start of the week."; break; case "Friday": $greeting = "TGIF!"; break; default: $greeting = "It's a regular day."; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Greeting Result</title> </head> <body> <h1>Greeting Result</h1> <?php // Display the greeting if it is set if (isset($greeting)) { echo "<p>{$greeting}</p>"; } else { echo "<p>Please select a day to get a greeting.</p>"; } ?> </body> </html>
Explanation:
Another example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Weekday or Weekend Checker</title> </head> <body> <h1>Weekday or Weekend Checker</h1> <form method="post" action="check_day.php"> <label for="dayNumber">Enter a number (1-7):</label> <input type="number" name="dayNumber" id="dayNumber" min="1" max="7" required> <button type="submit">Check</button> </form> </body> </html>
Explanation:
Now, let’s create the “check_day.php” file with the PHP code that uses the switch statement to determine whether the entered number represents a weekday or a weekend day.
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if the form is submitted using POST method // Retrieve the entered day number from the form $dayNumber = $_POST["dayNumber"]; // Use a switch statement to check whether the number represents a weekday or weekend day switch ($dayNumber) { case 1: case 2: case 3: case 4: case 5: $result = "Weekday"; break; case 6: case 7: $result = "Weekend"; break; default: $result = "Invalid day number. Please enter a number between 1 and 7."; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Result</title> </head> <body> <h1>Result</h1> <?php // Display the result if it is set if (isset($result)) { echo "<p>The entered number represents a {$result} day.</p>"; } else { echo "<p>Please enter a number to check whether it represents a weekday or weekend day.</p>"; } ?> </body> </html>
Explanation:
This example demonstrates how to use a switch statement in PHP to determine the type of day (weekday or weekend) based on input within the context of an HTML form.
In PHP, the break keyword is used in control structures like switch, while, do-while, and for to exit the current loop or switch statement and resume execution at the next statement after the loop or switch.
Let’s focus on the break keyword within the context of a switch statement:
$day = "Monday"; switch ($day) { case "Monday": echo "It's the start of the week."; break; // The break statement exits the switch statement here case "Friday": echo "TGIF!"; break; default: echo "It's a regular day."; }
Explanation:
Here’s an example without break:
$day = "Monday"; switch ($day) { case "Monday": echo "It's the start of the week."; // No break, so execution falls through to the next case case "Friday": echo "TGIF!"; break; default: echo "It's a regular day."; }
complete code example in html with explanation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Day of the Week Greeting</title> </head> <body> <h1>Day of the Week Greeting</h1> <form method="post" action="greet.php"> <label for="day">Select a day:</label> <select name="day" id="day"> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> <option value="Friday">Friday</option> <option value="Saturday">Saturday</option> <option value="Sunday">Sunday</option> </select> <button type="submit">Get Greeting</button> </form> </body> </html>
Explanation of the HTML code:
Now, let’s create the “greet.php” file with the PHP code that uses the switch statement to provide a greeting based on the selected day, along with explanations.
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if the form is submitted using POST method // Retrieve the selected day from the form $selectedDay = $_POST["day"]; // Use a switch statement to provide a greeting based on the selected day switch ($selectedDay) { case "Monday": $greeting = "It's the start of the week."; break; // Exit the switch statement after this case case "Friday": $greeting = "TGIF!"; break; // Exit the switch statement after this case default: $greeting = "It's a regular day."; // No break here, as this is the last case } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Greeting Result</title> </head> <body> <h1>Greeting Result</h1> <?php // Display the greeting if it is set if (isset($greeting)) { echo "<p>{$greeting}</p>"; } else { echo "<p>Please select a day to get a greeting.</p>"; } ?> </body> </html>
Explanation of the PHP code:
Here’s the basic syntax of a switch statement with the default case:
$variable = /* some value */; switch ($variable) { case value1: // code to be executed if $variable is equal to value1 break; case value2: // code to be executed if $variable is equal to value2 break; // more cases as needed default: // code to be executed if none of the cases match $variable }
In the example above, if none of the case values matches the value of $variable, the code within the default block will be executed.
Here’s a simple example using the default case:
$day = "Saturday"; switch ($day) { case "Monday": echo "It's the start of the week."; break; case "Friday": echo "TGIF!"; break; default: echo "It's a regular day."; }
Explanation:
Create the HTML file (index.html):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Greeting App</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Welcome to the Greeting App</h1> <form method="post" action="greet.php"> <label for="name">Your Name:</label> <input type="text" name="name" id="name" required> <label for="mood">Select your mood:</label> <select name="mood" id="mood"> <option value="happy">Happy </option> <option value="sad">Sad </option> <option value="excited">Excited </option> <option value="calm">Calm </option> </select> <button type="submit">Get Greeting</button> </form> </div> </body> </html>
Create the CSS file (styles.css):
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; align-items: center; justify-content: center; height: 100vh; } .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } form { display: flex; flex-direction: column; align-items: center; } label { margin-bottom: 8px; } input, select, button { margin-bottom: 16px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; } button { background-color: #4caf50; color: #fff; cursor: pointer; } Create the PHP f
File (greet.php):
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if the form is submitted using POST method // Retrieve the name and mood from the form $name = $_POST["name"]; $mood = $_POST["mood"]; // Use a switch statement to generate a greeting based on the selected mood switch ($mood) { case "happy": $greeting = "Hello, $name! It's great to see you're happy!"; break; case "sad": $greeting = "Hello, $name. Cheer up! Things will get better."; break; case "excited": $greeting = "Wow, $name! Exciting times ahead!"; break; case "calm": $greeting = "Hello, $name. Stay calm and enjoy your day."; break; default: $greeting = "Hello, $name! Hope you're having a good day!"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Greeting Result</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Greeting Result</h1> <?php // Display the greeting if it is set if (isset($greeting)) { echo "<p>{$greeting}</p>"; } else { echo "<p>Please fill out the form to get a personalized greeting.</p>"; } ?> <a href="index.html">Go Back</a> </div> </body> </html>
Explanation:
To run this application:
Let’s create another simple web application using HTML and PHP. This time, we’ll build a basic calculator that allows s to perform addition, subtraction, multiplication, and division. The application will take two numbers and an operation from the , and then display the result.
Create the HTML file (calculator.html):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Calculator</title> <link rel="stylesheet" href="calculator.css"> </head> <body> <div class="container"> <h1>Simple Calculator</h1> <form method="post" action="calculate.php"> <label for="num1">Enter first number:</label> <input type="number" name="num1" id="num1" required> <label for="operation">Select operation:</label> <select name="operation" id="operation" required> <option value="add">Addition (+)</option> <option value="subtract">Subtraction (-)</option> <option value="multiply">Multiplication (*)</option> <option value="divide">Division (/)</option> </select> <label for="num2">Enter second number:</label> <input type="number" name="num2" id="num2" required> <button type="submit">Calculate</button> </form> </div> </body> </html>
Create the CSS file (calculator.css):
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; align-items: center; justify-content: center; height: 100vh; } .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } form { display: flex; flex-direction: column; align-items: center; } label { margin-bottom: 8px; } input, select, button { margin-bottom: 16px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; } button { background-color: #4caf50; color: #fff; cursor: pointer; }
Create the PHP file (calculate.php):
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if the form is submitted using POST method // Retrieve the form data $num1 = $_POST["num1"]; $num2 = $_POST["num2"]; $operation = $_POST["operation"]; // Initialize the result variable $result = 0; // Perform the selected operation switch ($operation) { case "add": $result = $num1 + $num2; break; case "subtract": $result = $num1 - $num2; break; case "multiply": $result = $num1 * $num2; break; case "divide": if ($num2 != 0) { $result = $num1 / $num2; } else { $result = "Cannot divide by zero"; } break; default: $result = "Invalid operation"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calculation Result</title> <link rel="stylesheet" href="calculator.css"> </head> <body> <div class="container"> <h1>Calculation Result</h1> <?php // Display the result echo "<p>The result of the calculation is: $result</p>"; ?> <a href="calculator.html">Go Back</a> </div> </body> </html>
Explanation:
HTML File (index.html):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fruit Information App</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Fruit Information App</h1> <form method="post" action="fruit_info.php"> <label for="fruit">Select a fruit:</label> <select name="fruit" id="fruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> <option value="grape">Grape</option> </select> <button type="submit">Get Information</button> </form> </div> </body> </html>
CSS File (styles.css):
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; align-items: center; justify-content: center; height: 100vh; } .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } form { display: flex; flex-direction: column; align-items: center; } label { margin-bottom: 8px; } select, button { margin-bottom: 16px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; } button { background-color: #4caf50; color: #fff; cursor: pointer; }
PHP File (fruit_info.php):
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if the form is submitted using POST method // Retrieve the selected fruit from the form $selectedFruit = $_POST["fruit"]; // Use a switch statement to provide information about the selected fruit switch ($selectedFruit) { case "apple": $info = "Apples are a good source of fiber and vitamin C."; break; case "banana": $info = "Bananas are rich in potassium and provide a quick energy boost."; break; case "orange": $info = "Oranges are known for their high vitamin C content and antioxidants."; break; case "grape": $info = "Grapes are packed with antioxidants and are a great snack option."; break; default: $info = "Please select a valid fruit."; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fruit Information</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Fruit Information</h1> <?php // Display the information if it is set if (isset($info)) { echo "<p>{$info}</p>"; } else { echo "<p>Please select a fruit to get information.</p>"; } ?> <a href="index.html">Go Back</a> </div> </body> </html>
Here’s a quiz focused on the PHP switch statement:
Quiz: PHP Switch Statement
a) To define constants
b) To execute code based on multiple conditions
c) To create loops
d) To handle exceptions
a) stop
b) exit
c) break
d) end
a) It will result in a syntax error.
b) It will cause an infinite loop.
c) Execution will continue to the next case.
d) It will skip the current case and move to the default case.
a) To handle syntax errors
b) To execute when none of the cases match
c) To define a default value
d) To create a fallback loop
a) Array
b) String
c) Object
d) All of the above
a) It will result in a syntax error.
b) The switch statement will exit without executing any code.
c) It will trigger a runtime error.
d) It will execute the first case.
a) To define a switch expression
b) To create a loop
c) To start a switch statement
d) To exit a switch statement
a) No, it only supports equality comparisons.
b) Yes, it supports various types of comparisons.
c) Only for numeric values.
d) Only for string values.
a) It is more efficient for multiple conditions.
b) It can only handle simple conditions.
c) It is slower than if-else statements.
d) It does not support the use of variables.
a) It will result in a syntax error.
b) Execution will continue to the next case.
c) It will skip the current case and move to the default case.
d) It will exit the switch statement.
1-b) To execute code based on multiple conditions
2-c) break
3-c) Execution will continue to the next case.
4-b) To execute when none of the cases match
5-d) All of the above
6-b) The switch statement will exit without executing any code.
7-c) To start a switch statement
8-b) Yes, it supports various types of comparisons.
9-a) It is more efficient for multiple conditions.
10-b) Execution will continue to the next case.