LEARN TO CODE | PHP | 01 SERVER-SIDE FOUNDATIONS
01.3 Operators, selection and loops
Calculate values, choose between outcomes and repeat instructions using clear conditions and loop boundaries.
01 | CALCULATE BEFORE YOU DECIDE
Use the local development server from 01.1 . Save each complete example in its own .php file inside myWebsite, keep the server running and open its URL through http://127.0.0.1:8000/. Save changes and refresh the browser.
Short PHP-only examples can also be served as files: their output appears as the response body. Each example is independent unless stated otherwise. Browser HTML view, not the editor’s source view, shows the result.
<?php
$capacity = 12;
$members = 10;
$remaining = $capacity - $members;
echo $remaining;
EXPECTED OUTPUT
2
Arithmetic produces values we can use in decisions. A school-club page can calculate spaces before choosing whether to display “places available” or “full”.
02 | ARITHMETIC OPERATORS
| Operator | Example | Result |
|---|---|---|
| + | 7 + 3 | 10 |
| - | 7 - 3 | 4 |
| * | 7 * 3 | 21 |
| / | 7 / 2 | 3.5 |
| % | 7 % 3 | 1 |
| ** | 2 ** 3 | 8 |
% computes an integer remainder; it is useful for even/odd tests. Use intdiv(7, 2) for integer division, giving 3. Do not assume / behaves like SQLite integer division.
Use parentheses to show intended grouping. ($a + $b) * 2 differs from $a + $b * 2. Avoid division by zero; check the denominator when it can be zero.
03 | COMPARISON IS NOT ASSIGNMENT
<?php
var_dump(12 === '12');
var_dump(12 == '12');
var_dump(12 >= 10);
EXPECTED OUTPUT
bool(false) bool(true) bool(true)
=== compares value and type; == allows PHP’s comparison conversions. For predictable beginner code, prefer === when checking an exact expected value and type.
= assigns a value. !== tests non-identity. Numeric inequalities such as > and <= answer ordered comparisons. Do not use assignment accidentally inside a condition.
04 | SELECT WITH IF AND ELSE
<?php
$remaining = 2;
if ($remaining > 0) {
echo 'Places available';
} else {
echo 'Full';
}
EXPECTED OUTPUT
Places available
The condition is in parentheses. The body of a branch is the set of statements inside its braces. Exactly one of these two bodies runs.
Indent the body so the structure is visible. The closing brace ends that block; it is not a request to repeat it.
05 | ADD AN ELSEIF BRANCH
<?php
$remaining = 1;
if ($remaining === 0) {
echo 'Full';
} elseif ($remaining <= 2) {
echo 'Almost full';
} else {
echo 'Places available';
}
EXPECTED OUTPUT
Almost full
The first true branch is selected. In this example remaining is a known non-negative integer; negative counts would need separate validation or a different message.
Order matters. Putting a broad $remaining > 0 branch first would hide a later condition intended specifically for one or two places.
06 | COMBINE LOGICAL CONDITIONS
<?php
$yearLevel = 10;
$hasPermission = true;
if ($yearLevel >= 9 && $hasPermission) {
echo 'Eligible';
} else {
echo 'Check requirements';
}
EXPECTED OUTPUT
Eligible
&& means both conditions must be true, || means at least one, and ! negates a logical value. Parentheses help make mixed logic explicit.
Each comparison must be complete. ($yearLevel === 9 || $yearLevel === 10) tests two possible years; $yearLevel === 9 || 10 does not express the same question.
07 | REPEAT WITH FOR
<?php
for ($number = 1; $number <= 3; $number++) {
echo '<p>Round ' . $number . '</p>';
}
EXPECTED OUTPUT
Round 1 Round 2 Round 3
The for header has initialisation, condition and update, separated by semicolons. Set number to 1 once, test before each iteration, run the body if true, then increment number.
The loop body is the code inside the braces. An iteration is one execution of that body. The update is not a second copy of the initialisation.
| Value at test | Condition <= 3 | Action |
|---|---|---|
| 1 | true | Output Round 1, increment to 2 |
| 2 | true | Output Round 2, increment to 3 |
| 3 | true | Output Round 3, increment to 4 |
| 4 | false | Stop without another body execution |
08 | A WHILE LOOP CHECKS BEFORE THE BODY
<?php
$countdown = 3;
while ($countdown > 0) {
echo '<p>' . $countdown . '</p>';
$countdown--;
}
echo '<p>Go!</p>';
EXPECTED OUTPUT
3 2 1 Go!
Initialisation appears before while; the update is inside its body. Forgetting to decrease countdown would leave the condition true and the request running repeatedly.
A while loop may run zero times if the first test is false. Use for when a clear counter pattern fits; while when repetition naturally depends on a condition.
09 | TOTALS BUILD ON THEIR OLD VALUE
<?php
$total = 0;
for ($number = 1; $number <= 4; $number++) {
$total = $total + $number;
}
echo $total;
EXPECTED OUTPUT
10
The right side reads the old total and adds the current number. The assignment stores the new total. It is a step in a process, not a mathematical equation claiming two different values are always equal.
The running totals are 1, 3, 6 and 10. Initialise total before the loop; resetting it to zero inside the body would lose earlier contributions. $total += $number is a shorter form of the same update here.
10 | CONTROL OUTPUT AND CHECK BOUNDARIES
TRY IT YOURSELF
Output exactly five numbered list items, from 1 to 5, inside one unordered list.
Reveal guidance
<?php
echo '<ul>';
for ($number = 1; $number <= 5; $number++) {
echo '<li>Task ' . $number . '</li>';
}
echo '</ul>';
The list wrapper is outside the loop; the repeated li element is inside the body. Test the last counter value to avoid an off-by-one error.
break exits a loop and continue skips to its next iteration step. In a while loop, a continue placed before a required update can cause a stuck loop. Keep the initial examples straightforward until you can trace them confidently.
11 | INDEPENDENT CHALLENGE
TRY IT YOURSELF
Output numbers 1 to 6, labelling each as even or odd.
Reveal guidance
<?php
for ($number = 1; $number <= 6; $number++) {
if ($number % 2 === 0) {
echo '<p>' . $number . ': even</p>';
} else {
echo '<p>' . $number . ': odd</p>';
}
}
The loop controls which numbers are visited; the nested selection chooses the label for each number.
KEEP LEARNING
Previous page 01.4 Functions and arrays
References: PHP development server · Types · Arrays · HTML text escaping