The else
statement in PHP is used in conjunction with an if
statement to execute a block of code when the condition of the if
statement evaluates to false. It allows for decision-making in your code, enabling different execution paths based on conditions.
PHP Else Statement
1. Syntax of Else Statement
The basic syntax of an if-else
statement is as follows:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Here, if the condition
is true, the code inside the if
block will execute; otherwise, the code inside the else
block will run.
2. Example of Else Statement
Here's a simple example demonstrating the use of the else
statement:
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
In this example, since the variable $age
is 20 (which is greater than 18), the output will be:
You are eligible to vote.
3. Using Else If
You can also use else if
to test multiple conditions. The syntax is as follows:
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if both conditions are false
}
Here's an example:
$score = 75;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
For a score of 75, the output will be:
Grade: C
4. Nesting Else Statements
You can nest if-else
statements to create complex conditional logic. Here's an example:
$num = 0;
if ($num > 0) {
echo "$num is positive.";
} else {
if ($num < 0) {
echo "$num is negative.";
} else {
echo "$num is zero.";
}
}
The output for this example will be:
0 is zero.
5. Conclusion
The else
statement is an essential control structure in PHP, allowing for conditional execution of code based on different scenarios. By utilizing else
and else if
, you can create dynamic and responsive applications that adapt to user input and conditions.