PHP Control Flow and Loops — Conditionals, Loops, and Alternative Syntax
In this tutorial, you will learn about PHP Control Flow and Loops. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP control flow structures including if, else, switch, while, for, and foreach determine which code executes and how many times, forming the decision-making backbone of every PHP application.
Why It Matters
Without control flow, your program runs the same code every time from top to bottom. Conditionals let you check user permissions, validate form input, and show different content based on the situation. Loops let you Process arrays of data, generate HTML lists, and read database results. PHP's foreach loop is one of the most frequently used constructs in real applications -- it appears in almost every Laravel and WordPress template.
Real-World Use
A login system uses if/else to check whether a password matches. An e-commerce cart uses foreach to display each item and calculate totals. A blog uses while loops to paginate through database results. Laravel's Blade templates use @if and @foreach directives that compile to PHP's alternative syntax. DodaTech's dashboard uses foreach loops to display lists of scanned files and conditional checks to show status indicators.
What You Will Learn
- Using if, else, and elseif for conditional logic
- The switch statement for multi-way branching
- While and do-while loops for conditional iteration
- For loops for counted iteration
- Foreach loops for array and object traversal
- PHP's alternative syntax for templates
- Break, continue, and match expressions
Learning Path
flowchart LR A[Syntax and Variables] --> B[Control Flow and Loops
You are here] B --> C[Functions] C --> D[Arrays] D --> E[Superglobals] style B fill:#f90,color:#fff
If, Else, and Elseif
The if statement executes code only when a condition is true:
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
Expected output:
You are an adult.
For multiple conditions, chain elseif clauses:
<?php
$score = 85;
if ($score >= 90) {
$grade = 'A';
} elseif ($score >= 80) {
$grade = 'B';
} elseif ($score >= 70) {
$grade = 'C';
} elseif ($score >= 60) {
$grade = 'D';
} else {
$grade = 'F';
}
echo "Your grade is: $grade";
Expected output:
Your grade is: B
PHP evaluates conditions left to right. It stops at the first true condition. Order your conditions from most specific to most general.
Ternary Operator
The ternary operator is a shorthand if/else:
$age = 20;
$status = ($age >= 18) ? 'Adult' : 'Minor';
echo $status; // Adult
Null Coalescing Operator
The null coalescing operator ?? returns the first operand if it exists and is not null:
$username = $_GET['user'] ?? 'Guest';
// Equivalent to: isset($_GET['user']) ? $_GET['user'] : 'Guest'
PHP 8 introduced the null safe operator ?->:
$city = $user?->getAddress()?->city;
// Returns null if any method in the chain returns null, instead of error
Match Expression
PHP 8 introduced match as a more powerful alternative to switch:
<?php
$statusCode = 404;
$message = match ($statusCode) {
200 => 'OK',
301, 302 => 'Redirect',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown Status',
};
echo $message; // Not Found
Unlike switch, match uses strict comparison and returns a value. It also supports multiple conditions per arm with commas.
Switch Statement
The traditional switch is useful for simple value comparisons:
<?php
$day = 'Wednesday';
switch ($day) {
case 'Monday':
echo 'Start of work week';
break;
case 'Wednesday':
echo 'Midweek';
break;
case 'Friday':
echo 'Almost weekend';
break;
default:
echo 'Regular day';
}
Expected output:
Midweek
Always include break to prevent fall-through. Without it, PHP continues executing the next case. Fall-through can be useful intentionally:
switch ($day) {
case 'Saturday':
case 'Sunday':
echo 'Weekend!';
break;
default:
echo 'Weekday';
}
While and Do-While Loops
While loops repeat as long as a condition is true:
<?php
$count = 1;
while ($count <= 5) {
echo "Count: $count\n";
$count++;
}
Expected output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Do-while guarantees at least one execution:
<?php
$count = 1;
do {
echo "Count: $count\n";
$count++;
} while ($count <= 0);
Expected output:
Count: 1
The loop body runs once even though the condition is false.
For Loop
Use for when you know the exact number of iterations:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Iteration: $i\n";
}
Expected output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The for loop has three parts: initialization ($i = 0), condition ($i < 5), and increment ($i++). Any part can be empty, creating an infinite loop if you omit the condition.
Foreach Loop
Foreach is the most common PHP loop. It iterates over arrays and objects:
<?php
$fruits = ['Apple', 'Banana', 'Cherry'];
foreach ($fruits as $fruit) {
echo "$fruit\n";
}
Expected output:
Apple
Banana
Cherry
Access both key and value:
<?php
$user = ['name' => 'Alice', 'role' => 'admin', 'email' => 'alice@example.com'];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
Expected output:
name: Alice
role: admin
email: alice@example.com
Modifying Arrays in Foreach
To modify array values inside foreach, use the reference operator:
<?php
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as &$number) {
$number *= 2;
}
unset($number); // Break the reference
print_r($numbers);
Expected output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
Always unset the reference after the loop to avoid accidental modification later.
Alternative Syntax
PHP offers alternative syntax for control structures using colons and end keywords. This is commonly used in templates:
<?php if ($isLoggedIn): ?>
<p>Welcome back, <?= $username ?></p>
<?php elseif ($isAdmin): ?>
<p>Welcome, admin</p>
<?php else: ?>
<p>Please log in</p>
<?php endif; ?>
<?php foreach ($items as $item): ?>
<li><?= $item['name'] ?> - $<?= $item['price'] ?></li>
<?php endforeach; ?>
The alternative syntax replaces opening braces with a colon and closing braces with endif, endwhile, endfor, endforeach, or endswitch.
Break and Continue
Break exits a loop entirely. Continue skips to the next iteration:
<?php
for ($i = 0; $i < 10; $i++) {
if ($i === 3) {
continue; // Skip 3
}
if ($i === 7) {
break; // Stop at 7
}
echo "$i ";
}
Expected output:
0 1 2 4 5 6
Break accepts a numeric argument to break out of multiple nested loops:
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
if ($j === 2) {
break 2; // Breaks both loops
}
}
}
Common Mistakes
1. Forgetting Break in Switch
switch ($x) {
case 1:
doSomething(); // Falls through to case 2!
case 2:
doOther();
}
Always add break unless you intentionally want fall-through.
2. Infinite Loops
$i = 0;
while ($i < 10) {
// Forgot $i++
}
Ensure your loop variable changes toward the exit condition.
3. Confusing = and == in Conditions
if ($x = 5) { // Assigns 5 to $x, always true
Use == or === for comparison. The assignment = always evaluates to the assigned value.
4. Modifying Array While Foreaching by Value
foreach ($array as $item) {
$item = $item * 2; // Does not modify original array
}
Use &$item by reference to modify the original, or assign to a new array.
5. Using Loose Comparison in Match
match ('1') {
1 => 'integer', // Does not match in PHP 8 match (strict)
'1' => 'string', // Matches
};
Match uses strict comparison unlike switch which uses loose.
Practice Questions
What is the difference between switch and match in PHP? Switch uses loose comparison and falls through without break. Match uses strict comparison, returns a value, and does not fall through.
How do you break out of multiple nested loops? Use
break Nwhere N is the number of levels to break. Example:break 2breaks out of two nested loops.What is PHP's alternative syntax used for? It is used in templates to avoid braces that are hard to read when mixed with HTML. Use
:,endif,endforeach, etc.How does foreach handle references? Using
&$valuemodifies the original array. Always callunset($value)after the loop.Challenge: Write a PHP script that prints a multiplication table from 1 to 10 using nested loops, formatted as an HTML table.
Mini Project: FizzBuzz with Control Flow
Write a classic FizzBuzz program using PHP control flow:
<?php
for ($i = 1; $i <= 100; $i++) {
if ($i % 3 === 0 && $i % 5 === 0) {
echo "FizzBuzz\n";
} elseif ($i % 3 === 0) {
echo "Fizz\n";
} elseif ($i % 5 === 0) {
echo "Buzz\n";
} else {
echo "$i\n";
}
}
Expected output starts with:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
FAQ
What is Next
Now that you understand control flow, proceed to Functions to learn how to organize code into reusable blocks. Then read Arrays to master PHP's most versatile data structure.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro