This tutorial aims to provide an understanding of the 'if', 'else', and 'switch' control structures in PHP. These are fundamental components for controlling the flow of a PHP script based on different conditions.
By the end of this tutorial, you will be able to:
- Understand and use 'if', 'else', and 'switch' control structures in PHP.
- Write PHP scripts that react differently to different conditions.
A basic understanding of PHP and its syntax is required. Familiarity with the concepts of variables and data types in PHP will be beneficial.
The 'if' control structure is used to execute a block of code if a specified condition is true.
if (condition) {
// code to be executed if the condition is true
}
The 'else' control structure is used to execute a block of code if the same condition is false.
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
The 'elseif' control structure is a combination of 'if' and 'else'. It can be used to add more conditions.
if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
The 'switch' control structure is used to select one of many blocks of code to be executed.
switch (n) {
case label1:
// code to be executed if n=label1
break;
case label2:
// code to be executed if n=label2
break;
default:
// code to be executed if n is different from both label1 and label2
}
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
In this example, if the age is greater than or equal to 18, the message "You are eligible to vote." will be printed.
$age = 15;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
In this example, if the age is less than 18, the message "You are not eligible to vote." will be printed.
$score = 85;
if ($score > 90) {
echo "Excellent score!";
} elseif ($score > 70) {
echo "Good score!";
} else {
echo "Try harder!";
}
In this example, if the score is greater than 70 but less than or equal to 90, the message "Good score!" will be printed.
$day = "Mon";
switch ($day) {
case "Mon":
echo "Today is Monday.";
break;
case "Tue":
echo "Today is Tuesday.";
break;
default:
echo "Invalid day.";
}
In this example, if $day is "Mon", the message "Today is Monday." will be printed.
In this tutorial, we covered the 'if', 'else', and 'switch' control structures in PHP, how to use them, and their syntax. We also looked at practical examples of each control structure.
Continue your PHP learning journey by exploring more advanced control structures, such as loops and functions.