Control Statements in php
Control statements allow you to make decisions in your code. php supports if, else, elseif, switch, and the modern match expression.
Video Explanationâ

The if Statementâ
Executes code if a condition is true:
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
?>
The if...else Statementâ
Executes one block if true, another if false:
<?php
$score = 55;
if ($score >= 60) {
echo "Pass";
} else {
echo "Fail";
}
?>
The if...elseif...else Statementâ
Tests multiple conditions in sequence:
<?php
$marks = 75;
if ($marks >= 90) {
echo "Grade: A";
} elseif ($marks >= 75) {
echo "Grade: B";
} elseif ($marks >= 60) {
echo "Grade: C";
} else {
echo "Grade: F";
}
// Output: Grade: B
?>
Shorthand if (Ternary)â
<?php
$isLoggedIn = true;
echo $isLoggedIn ? "Welcome back!" : "Please log in.";
?>
The switch Statementâ
Tests a variable against multiple values:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week.";
break;
case "Friday":
echo "End of the work week!";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "Midweek day.";
}
?>
Note: Always use break to prevent fall-through to the next case.
The match Expression (php 8+)â
A cleaner alternative to switch with strict comparison:
<?php
$status = 2;
$message = match($status) {
1 => "Active",
2 => "Inactive",
3 => "Banned",
default => "Unknown"
};
echo $message; // Inactive
?>
Differences: switch vs matchâ
| Feature | switch | match |
|---|---|---|
| Comparison | Loose (==) | Strict (===) |
| Fall-through | Yes (needs break) | No |
| Returns value | No | Yes |
| Multiple conditions | Yes (stacked cases) | Yes (comma-separated) |
Nested if Statementsâ
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18) {
if ($hasLicense) {
echo "You can drive.";
} else {
echo "You need a license.";
}
} else {
echo "You are too young to drive.";
}
?>
Alternative Syntaxâ
php allows an alternative syntax for control structures, useful in HTML templates:
<?php $loggedIn = true; ?>
<?php if ($loggedIn): ?>
<p>Welcome, user!</p>
<?php else: ?>
<p>Please log in.</p>
<?php endif; ?>
Note: This alternative syntax using : and endif; / endswitch; is especially useful when mixing php with HTML markup.
Telemetry Integration
Completed working through this block? Sync progress to workspace.