Control structures in PHP define the flow of execution in a script. They allow developers to make decisions, loop through data, include files, and manage execution paths in flexible ways.
if, else, elseif / else if
The if statement is the most basic control structure, used to execute code conditionally.
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are under 18.";
}
Adding more conditions with elseif:
$score = 75;
if ($score >= 90) {
echo "Grade A";
} elseif ($score >= 75) {
echo "Grade B";
} else {
echo "Grade C";
}
Differences Between elseif and else if
Both elseif and else if are valid in PHP, but they differ slightly:
In practice, both usually work the same way:
$x = 1;
// Using elseif
if ($x == 1) {
echo "One";
} elseif ($x == 2) {
echo "Two";
}
// Using else if
if ($x == 1) {
echo "One";
} else if ($x == 2) {
echo "Two";
}
However, when using alternative syntax (with colons), elseif must be used. Example:
$x = 1;
// Works
if ($x == 1):
echo "One";
elseif ($x == 2):
echo "Two";
endif;
// Parse error: syntax error, unexpected token "if", expecting ":"
if ($x == 1):
echo "One";
else if ($x == 2):
echo "Two";
endif;
Alternative Syntax for Control Structures
PHP supports an alternative syntax, mostly used in templates:
<?php if ($loggedIn): ?>
<p>Welcome back, user!</p>
<?php else: ?>
<p>Please log in.</p>
<?php endif; ?>
This syntax uses : and endif; (or endforeach;, etc.) instead of curly braces.
while
The while loop runs as long as the condition is true:
$count = 1;
while ($count <= 5) {
echo $count;
$count++;
}
// 12345
do-while
The do-while loop executes at least once, even if the condition is false:
$count = 6;
do {
echo $count;
$count++;
} while ($count <= 5);
// 6
for
The for loop is commonly used when the number of iterations is known:
for ($i = 0; $i < 5; $i++) {
echo $i;
}
// 01234
foreach
The foreach loop is designed for arrays and objects.
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit;
}
// applebananacherry
- With Keys:
$user = ["name" => "Alice", "age" => 25];
foreach ($user as $key => $value) {
echo "${key}: ${value}";
}
// name: Aliceage: 25
- Unpacking Nested Arrays:
$points = [[1, 2], [3, 4], [5, 6]];
foreach ($points as [$x, $y]) {
echo "X: ${x}, Y: ${y} <br/>";
}
// X: 1, Y: 2
// X: 3, Y: 4
// X: 5, Y: 6
- Using References:
$numbers = [1, 2, 3];
foreach ($numbers as &$num) {
$num *= 2;
}
unset($num); // Important to prevent bugs later
print_r($numbers);
// [2, 4, 6]
break, continue
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
if ($i == 5) break;
echo $i;
}
// 124
switch
The switch statement is an alternative to multiple if-elseif checks:
$day = "Tue";
switch ($day) {
case "Mon":
echo "Start of the week";
break;
case "Tue":
case "Wed":
echo "Midweek";
break;
case "Fri":
echo "Weekend is near";
break;
default:
echo "Unknown day";
}
// Midweek
match
match is an expression that returns a value, similar to switch but stricter and more concise.
$status = 200;
$message = match ($status) {
200 => "OK",
404 => "Not Found",
500 => "Server Error",
default => "Unknown Status",
};
echo $message;
// OK
Unlike switch, match uses strict comparisons (===).
declare
The declare directive sets execution directives for a block of code.
- Ticks
A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare block's directive section.
declare(ticks=1);
register_tick_function(function () {
echo "Tick executed";
});
for ($i = 0; $i < 3; $i++) {
echo $i;
}
// Tick executed0Tick executed1Tick executed2Tick executedTick executed
- Encoding
A script's encoding can be specified per-script using the encoding directive.
declare(encoding='UTF-8');
- Strict Types
declare(strict_types=1);
function sum(int $a, int $b): int {
return $a + $b;
}
echo sum(5, 10); // 15
echo sum("5", "10"); // Fatal error: Uncaught TypeError: sum(): Argument #1 ($a) must be of type int, string given
return
Used inside functions to return a value:
function square($n) {
return $n * $n;
}
echo square(4); // 16
require, require_once
require includes a file, stopping execution if the file is missing:
require "config.php";
require_once ensures the file is included only once:
require_once "config.php";
include, include_once
include is similar to require, but only raises a warning if the file is missing:
include "menu.php";
include_once prevents multiple inclusions:
include_once "menu.php";
goto
goto allows jumping to a labeled section of code. It's rarely recommended, but PHP supports it.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) goto skip;
echo $i;
}
skip:
echo "Jumped here";
// 12 Jumped here
Source: Orkhan Alishov's notes