Control Structures
Site Admin
· 11 Sep 2026
· 6 views
Control Structures
Conditionals and loops direct the flow of your scripts. PHP supports the familiar structures from other C-style languages plus a few template-friendly alternatives.
if, elseif, else
<?php
$price = 120;
if ($price > 100) {
echo 'Expensive';
} elseif ($price > 50) {
echo 'Mid-range';
} else {
echo 'Cheap';
}
Conditions live inside parentheses and can combine with and, or, not, or the symbols &&, ||, and !.
switch for multiple branches
switch ($status) {
case 'draft':
echo 'Not published';
break;
case 'live':
echo 'Visible';
break;
default:
echo 'Unknown';
}
break stops fall-through into the next case.
for and foreach
for counts iterations, and foreach walks arrays:
for ($i = 1; $i <= 3; $i++) {
echo $i;
}
$tags = ['php', 'mysql', 'web'];
foreach ($tags as $tag) {
echo $tag;
}
Include the key form to get both parts:
foreach ($user as $key => $value) {
echo "$key: $value";
}
Alternative syntax for templates
if, while, foreach, and for have a colon form that reads cleanly between HTML blocks, ending with endif, endwhile, endforeach, or endfor.
while and do-while
while checks before each round, and do-while always runs at least once.
Key Points
- if, elseif, and else branch on conditions.
- switch plus break handles many fixed cases.
- for counts, foreach iterates arrays.
- Foreaching keys uses the key => value form.
- Colon syntax keeps templates readable.