About Lesson
What are conditional statements in PHP?
Conditional statements are used to perform different actions based on different conditions. PHP supports several conditional statements like if
, else
, elseif
, switch
.
🔷 Types of Conditional Statements in PHP
Statement | Description |
---|---|
if | Executes if the condition is true |
if...else | Executes one block if true, another if false |
if...elseif...else | Multiple conditions |
switch | Selects one of many blocks to execute |
✅ 1. if Statement
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
PHP
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
?>
✅ 2. if…else Statement
Syntax:
if (condition) {
// code if true
} else {
// code if false
}
PHP
<?php
$age = 16;
if ($age >= 18) {
echo "You can vote.";
} else {
echo "You are too young to vote.";
}
?>
✅3. if…elseif…else Statement
Syntax: if (condition1) {
// code if condition1 is true
} elseif (condition2) {
// code if condition2 is true
} else {
// code if none are true
}
Example:
PHP
<?php
$marks = 85;
if ($marks >= 90) {
echo "Grade: A";
} elseif ($marks >= 75) {
echo "Grade: B";
} elseif ($marks >= 60) {
echo "Grade: C";
} else {
echo "Fail";
}
?>
✅ 4. switch Statement
Used to avoid long if...elseif
chains.
Syntax: switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example:
PHP
<?php
$day = "Wednesday";
switch ($day) {
case "Monday":
echo "Today is Monday";
break;
case "Tuesday":
echo "Today is Tuesday";
break;
default:
echo "Another day";
}
?>
⚠️ Important Tips
- Always use
break
inswitch
to prevent fall-through. - Conditions must return boolean (
true
orfalse
) inif
statements. - Nesting is possible but should be avoided for readability.