Conditional Statements
Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
Types
- if statement
- if...else statement
- if...elseif...else statement
- nested if statement
if Statement
The if statement is used to execute a block of code only when a condition is true.
Syntax
if (condition) {
// code to execute if condition is true
}
Example
$number = 10;
// Check if number is greater than 5
if ($number > 5) {
echo "Number is greater than 5";
}
?>
if...else Statements
The if...else statement is used to execute one block of code if a condition is true, and another block if the condition is false.
Syntax
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example
$age = 16;
// Check condition
if ($age >= 18) {
echo "You are an adult";
} else {
echo "You are a minor";
}
?>
if...elseif...else Statement
The if...elseif...else statement is used when you need to check multiple conditions. It executes the first condition that is true. It is used to execute different blocks of code for more than two conditions.
Syntax
if (condition1) {
// code if condition1 is true
} elseif (condition2) {
// code if condition2 is true
} else {
// code if none of the conditions are true
}
Example
$marks = 65;
if ($marks >= 80) {
echo "Excellent";
} elseif ($marks >= 50) {
echo "Good";
} else {
echo "Fail";
}
?>
nested if statement
A nested if statement is an if statement placed inside another if statement. It is used when one condition depends on another condition being true.
Syntax
if (condition1) {
if (condition2) {
// code executes if both conditions are true
}
}
Example
$age = 20;
$hasID = true;
if ($age >= 18) {
if ($hasID == true) {
echo "You are allowed to enter";
}
}
?>