Conditional Statements in PHP
Types of Conditional Statements in PHP
Conditional statements in PHP are used to perform different actions based on different conditions, allowing for decision-making within a script. They evaluate expressions to either true or false and execute specific blocks of code accordingly. There are mainly 5 types of conditional statements in PHP:
- if statement
- if-else statement
- if-elseif-else statement
- Nested if statement
- Switch statement
1. if statement
In PHP, if statement executes the block of code inside the if statement if the expression is evaluated as true.
Syntax:
if (condition) {
// Code to be executed if condition is true
}
2. if-else statement
if-else statement executes the block of code inside the if statement if the expression is evaluated as true and executes the block of code inside the else statement if the expression is evaluated as false.
Syntax:
if (condition) {
// Code to be executed if true
} else {
// Code to be executed if false
}
3. if-elseif-else statement
This statement used to check multiple conditions in sequence. It executes different code based on which condition is true.
Syntax:
if ($condition1) {
// Code to be executed if condition1 is true
} elseif ($condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if all conditions are false
}
4. Nested if statement
Nested if statement is the if block inside another if block and the inner if statement implements only when a specific condition in the outer if statement is true.
Syntax:
if(condition){
//the code to be executed if condition is true.
if(condition){
// the code to be executed if condition is true.
}
}
5. Switch statement
In PHP, switch statement allows us to execute different blocks of code based on different conditions. It works similar like a if-else-if statement.
Syntax:
switch(condition) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code if no cases match
}