PHP Control Flow — Conditions & Loops Explained Simply
Control flow determines which code blocks execute based on conditions and how many times loops run — it’s the brain of your PHP application that makes decisions and repeats tasks automatically.
What You’ll Learn
By the end of this tutorial, you’ll write conditional logic with if/else, switch, and match, use all PHP loop types confidently, and mix PHP control flow with HTML templates cleanly.
Why Control Flow Matters
Every real application makes decisions. Durga Antivirus Pro uses conditional logic to decide whether a file is clean or infected based on signature matches. Doda Browser uses loops to scan through thousands of bookmarks. DodaZIP uses conditions to handle different archive formats. Without control flow, your code would run the same way every time — useless for dynamic applications.
Security note: Understanding Php Control Flow helps build more secure applications — a core principle at DodaTech, where tools like Durga Antivirus Pro and Doda Browser rely on solid implementation practices.
Control Flow Learning Path
flowchart LR
A[PHP Basics] --> B[Control Flow]
B --> C[Functions]
C --> D[Arrays]
D --> E[Forms]
B --> F{You Are Here}
style F fill:#f90,color:#fff
If/Else — Making Decisions (The “Why” First)
Think of if/else like a traffic light. If the light is green, go. If it’s red, stop. If it’s yellow, slow down. Your code needs the same logic:
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C or lower";
}
// Output: Grade: B
?>
Here’s how PHP reads this:
- Is
$score >= 90? No (85 < 90), skip to the next check - Is
$score >= 80? Yes (85 >= 80), so execute that block - Because a condition matched, the
elseblock is skipped entirely
Why the order matters: PHP checks conditions top-to-bottom. The first true condition wins. That’s why you check the highest grade first.
Alternative Syntax for Templates
When mixing PHP with HTML, PHP offers a cleaner colon-based syntax:
<?php if ($loggedIn): ?>
<h1>Welcome back, <?= $username ?>!</h1>
<?php else: ?>
<h1>Please sign up</h1>
<?php endif; ?>
The colon replaces the opening brace, and endif replaces the closing brace. This is much cleaner when you have HTML inside your conditions.
Switch — Many Choices, One Variable
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of work week";
break;
case "Friday":
echo "TGIF!";
break;
default:
echo "Weekend!";
}
?>
The “why”: Use switch when you’re checking one variable against many possible values. It’s cleaner than a long chain of elseif.
The gotcha: break is crucial. Without it, PHP falls through to the next case — it keeps executing even after a match.
Match (PHP 8+) — The Modern Alternative
<?php
$statusCode = 404;
$message = match ($statusCode) {
200 => "OK",
301, 302 => "Redirect",
404 => "Not Found",
500 => "Internal Server Error",
default => "Unknown Status",
};
echo $message; // Not Found
?>
match is like switch but better — it returns a value, uses strict comparison (===), and doesn’t need break. No more forgotten break bugs!
Loops — Doing Things Repeatedly
flowchart LR
A[for] --> B[Known count]
C[while] --> D[Condition at start]
E[do-while] --> F[Runs at least once]
G[foreach] --> H[Arrays]
For — When You Know the Count
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i\n";
}
?>
Think of for like counting laps in a race: “Start at 1, continue until 5, add 1 each lap.”
Foreach — The Array Specialist
<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "$color\n";
}
// With key => value
$user = ["name" => "Alice", "age" => 30];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
?>
foreach is the safest way to iterate arrays — you don’t need to know the length, and it automatically stops at the end.
Common Mistakes
1. Forgetting break in Switch
The most common PHP bug. Missing break causes fall-through:
switch ($day) {
case "Monday":
echo "Work day";
// No break! Falls through to Tuesday
case "Tuesday":
echo "Also a work day";
}2. Using = Instead of ==
// WRONG: assigns 5 to $x, which is truthy — always true!
if ($x = 5) { }
// RIGHT: comparison
if ($x == 5) { }3. Infinite While Loops
$i = 0;
while ($i < 10) {
// forgot $i++; — runs forever!
}4. Off-by-One in For Loops
for ($i = 0; $i <= 5; $i++) { } // 6 iterations (0,1,2,3,4,5)
for ($i = 0; $i < 5; $i++) { } // 5 iterations (0,1,2,3,4)
5. Modifying an Array While Iterating
foreach ($items as $key => $value) {
unset($items[$key]); // Can skip next element!
}Practice Questions
1. What’s the output of match (2) { 1 => "one", 2 => "two", default => "other" }?
"two". match uses strict comparison and returns the matching arm’s value.
2. When should you use foreach instead of for?
Always use foreach for iterating arrays. Use for only when you need a numeric counter or a fixed number of iterations unrelated to an array.
3. What happens if you omit break in a switch case?
PHP continues executing the next case (fall-through). This is sometimes intentional but usually a bug.
4. Why does if ($x = 5) always run?
= is assignment, not comparison. It sets $x to 5 and returns 5 (truthy). PHP evaluates truthy as true.
5. Challenge: Write a script that prints the multiplication table for a given number (1-10).
<?php
$num = 7;
for ($i = 1; $i <= 10; $i++) {
echo "$num × $i = " . ($num * $i) . "\n";
}
?>
FAQ
Try It Yourself
Create a number guessing game (guess.php):
<?php session_start();
if (!isset($_SESSION["target"])) {
$_SESSION["target"] = rand(1, 100);
$_SESSION["attempts"] = 0;
}
$message = "";
$guess = $_POST["guess"] ?? null;
if ($guess !== null) {
$_SESSION["attempts"]++;
if ($guess < $_SESSION["target"]) {
$message = "Too low!";
} elseif ($guess > $_SESSION["target"]) {
$message = "Too high!";
} else {
$message = "Correct in {$_SESSION["attempts"]} attempts!";
session_destroy();
}
} ?>
<form method="post">
<input type="number" name="guess" min="1" max="100" required>
<button type="submit">Guess</button>
<p><?= $message ?></p>
</form>
Run with php -S localhost:8000 and open http://localhost:8000/guess.php.
What’s Next
| Lesson | Description |
|---|---|
| https://tutorials.dodatech.com/backend/php/php-functions/ | Write reusable code blocks |
| https://tutorials.dodatech.com/backend/php/php-arrays/ | Master PHP arrays |
| https://tutorials.dodatech.com/backend/php/php-forms/ | Form handling and validation |
| MySQL | Database-driven conditions |
| Laravel | Control flow in MVC frameworks |
What’s Next
Congratulations on completing this Php Control Flow tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro