What is it?
Conditional statements let your program make decisions at runtime based on whether a condition is true or false.
Why does it matter?
Almost every feature in software involves a decision: is the user logged in? Is the payment valid? Is the stock available? Without conditionals none of this is possible.
Master PHP conditional statements — if, else, elseif, and switch with practical examples.
Real-World Use Cases
- 🔐 User authentication - Check if a session exists and redirect to login if not — the most common if-else pattern in PHP.
- 🎓 Grading systems - Assign letter grades based on marks ranges using elseif chains — perfect for ordered conditions.
- 📦 Order status display - Use switch to map status codes like 'pending', 'shipped', 'delivered' to human-readable labels.
- 💳 Payment gateway routing - Route to different payment processors based on currency or region using if-elseif blocks.
if-else and elseif
<!--?php
$marks = 75;
if ($marks -->= 90) echo 'Grade: A';
elseif ($marks >= 75) echo 'Grade: B';
elseif ($marks >= 60) echo 'Grade: C';
else echo 'Grade: F';
// Output: Grade: B
Ternary and Null Coalescing
<!--?php
$age = 20;
$status = ($age -->= 18) ? 'Adult' : 'Minor';
echo $status; // Adult
// Null coalescing — perfect for missing form fields
$user = $_GET['name'] ?? 'Guest';
echo $user; // Guest if name not in URL
Q: When should I use switch instead of if-elseif?
Use switch when comparing one variable against many fixed values. Use if-elseif for ranges or complex conditions involving multiple variables.
Comments (0)
No comments yet. Be the first!
Leave a Comment