As a prerequisite to understanding conditional statements in PHP, a thorough comprehension of PHP operators is required. We have extensively covered operators in our previous lesson, which you can review here. We hope you've mastered operators, as they are often used in conjunction with if-else and switch-case statements. For instance, experienced programmers frequently use the ternary operator instead of a simple if-else statement. Make sure you're comfortable with operators before moving on to this lesson. Conditional expressions are a fundamental component of any programming language. In PHP programming language, conditional statements play a crucial role in controlling the flow of execution. They enable programs to branch based on specific conditions. In PHP, conditional statements are used to make decisions and execute different blocks of code depending on whether a certain condition is true or false. The most commonly used conditional statements in PHP programming language are:
if statement
if-else statement
If-elseif-else statement
switch statement
Conditional statements in PHP offer a flexible way to control the flow of program execution, making code dynamic and adaptable to various scenarios. If, else, elseif, switch, and even the ternary operator are the primary tools programmers use to implement condition-based logic. In the PHP programming language, they are most often used for the following scenarios:
Data validation:
- Checking if the user has entered the correct password
- Checking if the email address is in the correct format
- Checking if the selected option is valid
Controlling the flow of execution:
- Executing different parts of the code depending on the value of a variable
- Skipping certain parts of the code if a certain condition is met
- Repeating a certain part of the code until a condition is met (loops)
Displaying different content based on the user:
- Displaying a different page layout for logged-in and logged-out users
- Displaying different content based on the user's role (admin, moderator, user)
Creating simple calculators and games:
- Calculating results based on input data
- Checking if the user has guessed the correct answer
Form validation:
- Checking if all required fields are filled
- Checking if the data format is correct
What is an if-else Statement and How is It used?
The if-else statement in PHP allows us to control the
flow of program execution based on the truth of a given condition. In other
words, the if block is executed when the given condition is true, i.e., when it
returns a true value, while the else block is executed when the condition is
false, i.e., when it returns a false value.
If a specified condition is true.
if (condition) {
// Code to execute if condition is true
}
If the condition of the preceding if statement evaluates to
false.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
If evaluate multiple conditions sequentially and execute the
corresponding block of code if any condition is true.
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if both condition1 and condition2 are false
}
Keep in mind that each if-else block can contain other if-else blocks within itself. This is called nesting and it allows for the creation of more complex logical structures. Nesting if-else statements is a great way to make more complex decisions in our code. Too much nesting can make code harder to understand, so it's good to be mindful of that.
To get us started with the practical example and programming of our PHP tutorial, initiate your Apache Server and Visual Studio Code by executing the following commands in your terminal.
manuel@manuel-virtual-machine:~$ sudo apt-get update
manuel@manuel-virtual-machine:~$ sudo apt-get upgrade
manuel@manuel-virtual-machine:~$ clear
manuel@manuel-virtual-machine:~$ cd /opt/lampp
manuel@manuel-virtual-machine:~$ ls
manuel@manuel-virtual-machine:/opt/lampp$ sudo
./manager-linux-x64.run
When the XAMPP manager window opens, start the Apache Web Server and open Visual Studio Code. Click on index.php, then in the code editor panel, modify the following part of the code.
<?php
<br/><br/><br/><br/><br/>
<!--
<h5
class="bg-dark text-light text-center py-2" id="footer">
Copyright © 2023 <strong>Manuel Radovanovic</strong>
All rights reserved.
</h5>
-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
You can now create a new file called lesson04.php. We'll use this file to showcase nested if-else statements. These statements will help us determine which HTML radio button and color the user has chosen. Once the user clicks the "Selected color" button, our code will display a colored square that matches their selection. Input the following HTML and PHP code.
<?php
// Sets the page title
$title = 'Lesson 4';
require_once '../includes/header.php';
?>
Conditional
Statement if-else
</h2>
<form method="post">
<h4>Choose one color</h4>
<input type="radio" value="red" name="colors"/> Red <br/>
<input type="radio" value="yellow" name="colors"/> Yellow <br/>
<input type="radio" value="green" name="colors"/> Green <br/>
<input type="radio" value="purple" name="colors"/> Purple <br/>
<br/>
</form>
// Checks if the form has been submitted
if (isset($_POST['submit'])) {
if (!empty($_POST['colors'])) {
// Stores
the selected color
$selected_value = $_POST['colors'];
echo 'You have selected ' . $selected_value . ' color.';
echo '<br><br>';
if ($selected_value == 'blue') {
echo '<div
style="width:200px; height:200px; border:1px solid #000;
background-color:blue;"></div>';
} elseif ($selected_value == 'red') {
echo '<div
style="width:200px; height:200px; border:1px solid #000;
background-color:red;"></div>';
} elseif ($selected_value == 'yellow') {
echo '<div
style="width:200px; height:200px; border:1px solid #000;
background-color:yellow;"></div>';
} elseif ($selected_value == 'green') {
echo '<div
style="width:200px; height:200px; border:1px solid #000;
background-color:green;"></div>';
} elseif ($selected_value == 'purple') {
echo '<div
style="width:200px; height:200px; border:1px solid #000;
background-color:purple;"></div>';
}
} else {
// Displays an error message if no color is selected
echo 'Choose one color.';
}
}
?>
</div>
<!-- footer ->
<?php require_once '../includes/footer.php'; ?>
When you run this website, the result will be as in the following image.
You can see how this whole process looks like in the following video, too.
A switch-case statement offers a concise mechanism for evaluating a single expression against a list of constant values. This construct provides an alternative to lengthy chains of if-else statements, enhancing code readability and maintainability. It's particularly useful for scenarios where a variable can assume a finite set of discrete values. Common applications include:
- Implementing multi-option menus where each selection triggers a specific action.
- Handling diverse user inputs by executing different code blocks based on the input value.
- Responding to various states or conditions within an application, such as days of the week, user roles, or data types.
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases can be added as needed
default:
// Code to execute if expression doesn't match any case
}
The switch-case statement is a valuable tool for controlling
program flow based on the value of a variable. It offers a clear and efficient
way to handle multiple conditions. While nested switch-case statements are
technically possible, excessive nesting can hinder code readability and
maintainability. It's advisable to limit the depth of nested switch-case statements
and consider alternative approaches, such as using functions or object-oriented
programming techniques, to manage complex logic.
As a practical PHP exercise, let's implement a typical "Days of the Week" switch-case statement often used as a beginner's example. However, we'll introduce some variations to make it more interesting. To begin, we'll modify our index.php file.
<?php
$title = 'PHP Tutorial';
require_once 'includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">Contents</h2>
<div class="container">
<div>
Then create a new file lesson05.php and enter the following code.
<?php
// Sets the page title
$title = 'Lesson 5';
require_once '../includes/header.php';
?>
Conditional
Statement switch-case
</h2>
<form method="post">
<h4>While most of the USA
considers Sunday to be the first day of the week,
the International Organization for Standardization (ISO)
has standardized
Monday as the first day. This serves as a prime example of
international
standardization.</h4>
<label for="day">Enter a day of the week
(number from 1 to 7):</label>
<input type="number" name="day" id="day" min="1" max="7">
<input type="submit" value="Check">
</form>
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$day = $_POST['day'];
case 1:
echo "Monday is the first
day of the week.";
break;
case 2:
echo "Tuesday is the
second day of the week.";
break;
case 3:
echo "Wednesday is the
third day of the week.";
break;
case 4:
echo "Thursday is the
fourth day of the week.";
break;
case 5:
echo "Friday is the fifth
day of the week.";
break;
case 6:
echo "Saturday is the
sixth day of the week.";
break;
case 7:
echo "Sunday is the
seventh day of the week.";
break;
default:
echo "The entered number
is not valid. Please enter a number from 1 to 7.";
}
}
?>
</div>
<!-- footer ->
<?php require_once '../includes/footer.php'; ?>
When you run this website, the result will be as in the following image.
No comments:
Post a Comment