What Are We Doing in This Post?
So far PHP has been doing exactly what we tell it — store this, print that, calculate this. It has no brain of its own yet.
In this episode, we give PHP a brain.
Conditionals let PHP look at a situation and decide what to do based on the data. This is the foundation of all real programming logic. Every feature you have ever used on a website — login checks, permission systems, discount calculators, form validation — uses conditionals at its core.
The if Statement — The Most Basic Decision
Real world analogy: You check the weather before leaving home. If it is raining, you take an umbrella. That is an if statement in real life.
In PHP:
<?php
$is_raining = true;
if ($is_raining) { echo "Take an umbrella."; }
?>
Output: Take an umbrella.
The code inside the curly braces only runs if the condition inside the parentheses is true. If $is_raining were false, nothing would be printed at all.
The structure is always the same: the keyword if, then the condition in parentheses, then the code to run inside curly braces.
The else Statement — Handling the Other Case
What if you want to do something when the condition is false as well?
<?php
$is_raining = false;
if ($is_raining) { echo "Take an umbrella."; } else { echo "No umbrella needed. Enjoy the sun."; }
?>
Output: No umbrella needed. Enjoy the sun.
else runs when the if condition is false. You always get exactly one of the two outcomes — never both, never neither.
The elseif Statement — Handling Multiple Cases
Sometimes there are more than two possible situations.
Real world analogy: A traffic light. If it is green, go. If it is yellow, slow down. If it is red, stop.
<?php
$light = "yellow";
if ($light == "green") { echo "Go."; } elseif ($light == "yellow") { echo "Slow down."; } elseif ($light == "red") { echo "Stop."; } else { echo "Unknown signal. Proceed with caution."; }
?>
Output: Slow down.
PHP checks each condition from top to bottom. The moment it finds a true condition, it runs that block and skips everything else. The final else at the bottom is a safety net — it catches any case that none of the above conditions matched.
You can chain as many elseif blocks as you need.
Comparison Operators Inside Conditions
Now the comparison operators from Episode 04 become truly useful. Let us build a real example — an age-based access checker.
<?php
$age = 16;
if ($age >= 18) { echo "Access granted. Welcome."; } elseif ($age >= 13) { echo "Access granted for teens. Some content is restricted."; } else { echo "Access denied. You must be at least 13 years old."; }
?>
Output: Access granted for teens. Some content is restricted.
Change the value of $age and run it again. Try 10, 15, 20. Watch the output change. This is dynamic logic — the same code produces different results based on the data.
Logical Operators Inside Conditions
You can combine multiple conditions in a single if statement using the logical operators from Episode 04.
<?php
$age = 20; $has_ticket = true;
if ($age >= 18 && $has_ticket) { echo "Entry allowed."; } else { echo "Entry denied."; }
?>
Output: Entry allowed.
Both conditions must be true for entry to be allowed. Change $has_ticket to false and the output becomes Entry denied — even though the age condition is still true.
<?php
$is_member = false; $has_coupon = true;
if ($is_member || $has_coupon) { echo "Discount applied."; } else { echo "No discount available."; }
?>
Output: Discount applied.
Either condition being true is enough. The user has a coupon, so they get the discount even though they are not a member.
Nested if Statements — Decisions Inside Decisions
You can put an if statement inside another if statement. This is called nesting.
<?php
$is_logged_in = true; $is_admin = false;
if ($is_logged_in) { echo "Welcome back!"; echo "<br>";
if ($is_admin) {
echo "You have admin access.";
} else {
echo "You have standard user access.";
}
} else { echo "Please log in to continue."; }
?>
Output:
Welcome back! You have standard user access.
The outer if checks if the user is logged in at all. Only after confirming that does the inner if check their role. This mirrors exactly how login and permission systems work on real websites.
The switch Statement — Cleaner Multiple Choice
When you have one variable being compared against many specific values, elseif chains can get messy. The switch statement is cleaner for this situation.
<?php
$day = "Wednesday";
switch ($day) { case "Monday": echo "Start of the work week. Stay focused."; break; case "Wednesday": echo "Midweek. You are halfway there."; break; case "Friday": echo "Almost the weekend!"; break; case "Saturday": case "Sunday": echo "Weekend. Rest and recharge."; break; default: echo "Just another day. Keep going."; }
?>
Output: Midweek. You are halfway there.
switch takes the variable and checks it against each case from top to bottom. When it finds a match, it runs that block. The break keyword tells PHP to exit the switch after running the matched case. Without break, PHP would continue running every case below the match — almost always not what you want.
The default block at the bottom works like else — it runs when nothing else matched.
Notice Saturday and Sunday share the same output. You can stack cases on top of each other when they should produce the same result.
The Ternary Operator — Short if/else in One Line
When your condition is simple and you just want to assign one of two values, PHP gives you a shortcut called the ternary operator.
<?php
$age = 20; $status = ($age >= 18) ? "Adult" : "Minor"; echo $status;
?>
Output: Adult
The structure is: condition ? value if true : value if false
Read it as: "Is age greater than or equal to 18? If yes, use Adult. If no, use Minor."
Use ternary for simple one-line decisions. Use full if/else for anything more complex — readability matters.
The Null Coalescing Operator — Handling Missing Values
This one is specific to PHP and extremely useful when working with form data.
<?php
$username = null; $display_name = $username ?? "Guest"; echo $display_name;
?>
Output: Guest
The ?? operator checks if the left side is null or not set. If it is null, it uses the right side as the fallback value. If it is not null, it uses the left side.
Real world use: a user visits your page without logging in. Their username is null. You want to display "Guest" instead of nothing. This operator handles that in one clean line.
A Real World Example — Student Grade Calculator
Let us build a complete practical example combining everything from this episode.
Create a new file in your phplearning folder called grades.php and write this:
<!DOCTYPE html> <html> <head> <title>Grade Calculator</title> </head> <body>
<?php
$student_name = "Gagan"; $score = 78;
if ($score >= 90) { $grade = "A"; $message = "Outstanding performance!"; } elseif ($score >= 75) { $grade = "B"; $message = "Good work. Keep it up."; } elseif ($score >= 60) { $grade = "C"; $message = "Average performance. You can do better."; } elseif ($score >= 40) { $grade = "D"; $message = "Below average. More effort needed."; } else { $grade = "F"; $message = "Failed. Please review the material."; }
$result = ($score >= 40) ? "Pass" : "Fail";
echo "<h2>Result Card</h2>"; echo "<p>Student: $student_name</p>"; echo "<p>Score: $score / 100</p>"; echo "<p>Grade: $grade</p>"; echo "<p>Result: $result</p>"; echo "<p>Remark: $message</p>";
?>
</body> </html>
Visit http://localhost:8080/phplearning/grades.php
Try changing $score to different values — 95, 72, 55, 30 — and refresh the page each time. Watch every output change based on the score. This is exactly how a real school management system calculates and displays grades.
What Did We Learn in This Post?
if runs a block of code only when a condition is true.
else handles the case when the if condition is false.
elseif handles multiple conditions in sequence — PHP checks each one top to bottom and runs the first true one.
Logical operators AND and OR let you combine multiple conditions inside a single if statement.
Nested if statements let you put decisions inside decisions — essential for role and permission systems.
switch is cleaner than long elseif chains when comparing one variable against many specific values.
The ternary operator is a one-line shortcut for simple if/else assignments.
The null coalescing operator ?? provides a fallback value when a variable is null or not set.
What is Coming in Episode 06?
Now that PHP can make decisions, we need to teach it to repeat tasks.
Episode 06 covers loops — while, do while, for, and foreach. Loops are how PHP processes lists of data, generates repeated HTML, and handles large amounts of information without you writing the same code a hundred times.
See you in the next one.
Next Episode: Loops — Teaching PHP to Repeat Tasks Automatically
This is Episode 05 of the PHP and Laravel — Zero to Hero series.
No comments:
Post a Comment