Conditional Statements in PHP
Conditional statements are used to control the flow of a program. They allow PHP to make decisions and execute code only if certain conditions are met.
🧠 Why Use Conditional Statements?
- To control what code runs and when
- To validate inputs
- To respond to user actions
- To display different outputs dynamically
✅ 1. if Statement
Executes code only if the condition is true.
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}
🔄 2. if...else Statement
Chooses between two blocks of code.
$marks = 45;
if ($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
🔁 3. if...elseif...else Statement
Tests multiple conditions in sequence.
$score = 85;
if ($score >= 90) {
echo "Grade A";
} elseif ($score >= 75) {
echo "Grade B";
} elseif ($score >= 60) {
echo "Grade C";
} else {
echo "Fail";
}
🔃 4. switch Statement
Evaluates a variable and matches it against different cases.
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
default:
echo "Unknown day";
}
⚡ 5. Ternary Operator
A shorthand way to write simple if...else conditions in one line.
$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
📝 Summary Table
Statement Type | Description | Use Case |
---|---|---|
if | Run code if condition is true | One simple condition |
if...else | Choose between two options | Yes/No, True/False logic |
if...elseif...else | Test multiple conditions | Multiple outcomes |
switch | Test one variable against many values | Cleaner than many ifs |
ternary | Short if...else on one line | Compact decisions in output |
💡 Best Practices:
- Use
===
for strict comparison (value + type) - Don't overuse nested
if...else
; useswitch
when applicable - Use ternary for short conditions, but not for complex logic
0 Comments