In PHP, the if and elseif statements are used for conditional execution of code based on certain conditions. These statements allow you to control the flow of your PHP scripts by executing different blocks of code depending on whether specific conditions are true or false.
1. if Statement:
The if statement is the most basic conditional statement in PHP. It allows you to execute a block of code if a specified condition evaluates to true. The general syntax of the if statement is as follows:
if (condition) {
// code to be executed if the condition is true
}
- The condition is an expression that evaluates to either true or false.
- If the condition is true, the code block inside the if statement is executed.
- If the condition is false, the code block is skipped, and the execution continues with the next statement after the if block.
Example:
$age = 25;
if ($age >= 18) {
echo “You are an adult.”;
}
2. elseif Statement:
The elseif statement is used to add additional conditions to an if statement. It allows you to test multiple conditions sequentially and execute different blocks of code based on the first condition that evaluates to true. The general syntax of the elseif statement is as follows:
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
}
- You can have multiple elseif blocks to test additional conditions.
- The else block is optional and is executed if none of the preceding conditions are true.
Example:
$grade = 75;
if ($grade >= 90)
{
echo “Excellent!”;
}
elseif ($grade >= 80)
{
echo “Good!”;
}
elseif ($grade >= 70)
{
echo “Average!”;
}
Else
{
echo “Needs improvement.”;
}
In this example:
- If the grade is 75, it will execute the code block inside the elseif ($grade >= 70) statement, resulting in the output “Average!”.
- The else block is not executed because the condition $grade >= 70 evaluates to true before reaching it.
Using if and elseif statements allows you to create flexible and powerful logic in your PHP scripts, enabling you to handle various scenarios based on different conditions.