Objective. Students implement PHP programs using if/elseif/else, switch, for, while, foreach, and user-defined functions that accept parameters and return values, and manipulate indexed and associative arrays using built-in array functions
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
Control flow statements let your script make decisions and repeat work. PHP shares C-style syntax with many languages, so these patterns will look familiar once you learn them.
if / elseif / else evaluates a condition and branches:
```php
if ($score >= 90) {
$grade = 'A';
} elseif ($score >= 80) {
$grade = 'B';
} elseif ($score >= 70) {
$grade = 'C';
} else {
$grade = 'F';
}
```
Conditions are checked top-to-bottom; the first true branch runs and the rest are skipped.
switch compares one expression against many values using strict equality. It is cleaner than a long if/elseif chain when you are matching a single variable to specific values. Always include `break` at the end of each case; without it, execution "falls through" to the next case.
```php
switch ($day) {
case 'Monday':
echo 'Start of the week';
break;
case 'Friday':
echo 'Almost weekend';
break;
default:
echo 'Midweek';
}
```
for loops are used when the number of iterations is known:
```php
for ($i = 0; $i < 10; $i++) {
echo $i;
}
```
while loops run as long as a condition is true; use them when the iteration count is unknown:
```php
while ($input !== 'quit') {
$input = readline('Enter command: ');
}
```
foreach is designed for arrays and is the standard way to iterate over them in PHP:
```php
foreach ($students as $name => $score) {
echo "$name scored $score";
}
```
The `$name => $score` syntax unpacks both the key and the value from an associative array.
A function groups reusable logic under a name. Define it with `function`, list parameters in parentheses, and use `return` to send a value back to the caller:
```php
function letterGrade(int $score): string {
if ($score >= 90) return 'A';
if ($score >= 80) return 'B';
if ($score >= 70) return 'C';
if ($score >= 60) return 'D';
return 'F';
}
```
Type hints (`int`, `string`) are optional but recommended: they document intent and catch type errors early. Call the function by name and pass arguments: `$grade = letterGrade(85);`
PHP arrays are ordered maps. An indexed array uses integer keys starting at 0:
```php
$colors = ['red', 'green', 'blue'];
```
An associative array uses string keys you define:
```php
$scores = ['Alice' => 92, 'Bob' => 78, 'Carol' => 85];
```
You can mix key types, but keep them consistent for clarity.
| Function | What it does |
|---|---|
| `array_map` | Applies a callback to every element and returns a new array |
| `array_filter` | Returns elements for which the callback returns true |
| `usort` | Sorts an array using a user-supplied comparison function |
| `array_slice` | Extracts a portion of an array by offset and length |
| `in_array` | Returns true if a value exists anywhere in the array |
Always look functions up on php.net before using them. The manual lists every parameter, return type, version notes, and user comments with edge-case warnings.
Add `error_reporting(E_ALL);` and `ini_set('display_errors', '1');` at the top of any script you are debugging. This tells PHP to surface every notice, warning, and error in the browser or terminal output instead of silently swallowing them.
When you encounter a bug:
1. Read the error message fully — it includes the file name and line number.
2. Hand-trace the code: step through it on paper, tracking the value of each variable at each line.
3. Add temporary `echo` or `var_dump()` statements to inspect actual values at runtime.
4. Fix one issue at a time and re-run; fixing several things at once makes it impossible to know which change worked.
5. Record the bug and fix in your lab log so the pattern sticks.
There are no electrical or chemical hazards in this lab, but professional discipline matters:
A PHP script can write HTML directly. Mix PHP and HTML carefully:
```php
echo '<table border="1">';
echo '<tr><th>Name</th><th>Score</th><th>Grade</th></tr>';
foreach ($students as $name => $score) {
$grade = letterGrade($score);
echo "<tr><td>" . htmlspecialchars($name) . "</td>";
echo "<td>$score</td><td>$grade</td></tr>";
}
echo '</table>';
```
Note the use of `htmlspecialchars()` on the name — a good habit even in lab work.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.