PHP Conditional Statements
Conditional statements in PHP are used to execute different blocks of code based on whether a certain condition evaluates to true or false.
Very often when we write code, we want to perform different actions for different conditions. we can use conditional statements in our code to do this.
In PHP we have the following conditional statements:
- if statement – executes some code if one condition is true.
- if..else statement – executes some code if a condition is true and another code if that condition is false.
- if..elseif…else statement – executes different codes for more than two conditions.
- Switch statement – selects one of many blocks of code to be executed.
1) if Statement:
The ‘if’ statement allows us to execute a block of code if a specified condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
Example of ‘if’ statement:-
= 18) {
echo "You are eligible to vote.";
}
?>
Output :
You are eligible to vote.
2) if-else Statement:
The if-else statement allows us to execute one block of code if the condition is true and another block if the condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example of ‘if-else ’ statement:-
= 40) {
echo "You passed!";
} else {
echo "You failed.";
}
?>
Output:
You failed.
3) if-elseif-else Statement:
The if-elseif-else statement allows us to test multiple conditions and execute different code blocks accordingly.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example of ‘if-elseif-else’ statement-:
Output :
You're Good!
4) Switch Statement:
The switch statement is used when we have multiple possible conditions to test.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
…
default:
code to be executed if n is different from all labels;
}
Example of ‘switch’ statement:-
Output:-
Your favorite color is black!