🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 3
TEC-WEB46-03 · Lesson 3 · 13 clock hours · lab

PHP Control Flow, Functions, and Arrays

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

⚠ Pending professional review

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.

PHP Control Flow

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';

}

```

PHP Loops

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.

User-Defined Functions

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

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.

Useful Built-in Array Functions

| 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.

Debugging PHP

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.

Safety and Professional Habits

There are no electrical or chemical hazards in this lab, but professional discipline matters:

Generating an HTML Table in PHP

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.

Key terms10

associative arrayA PHP array that uses named string keys instead of automatic integer indexes, allowing values to be accessed by a meaningful name such as a student's name.
foreachA PHP loop construct designed for iterating over arrays; the syntax `foreach ($array as $key => $value)` unpacks both the key and value of each element on each iteration.
user-defined functionA named, reusable block of PHP code declared with the `function` keyword that accepts parameters and optionally returns a value to the caller.
return statementThe PHP statement that ends a function's execution and sends a value back to the code that called the function.
array_mapA PHP built-in function that applies a callback function to every element of an array and returns a new array containing the transformed values.
error_reporting(E_ALL)A PHP configuration call that instructs the interpreter to report all types of errors, warnings, and notices, making bugs visible during development and debugging.
type hintAn optional declaration in a PHP function signature that specifies the expected data type of a parameter or return value, improving readability and catching type mismatches early.
hand-tracingA debugging technique in which a programmer manually steps through source code on paper or a whiteboard, tracking the value of each variable line by line to locate logic errors.
fall-throughThe behavior in a PHP switch statement where execution continues into the next case block when a `break` statement is missing, often causing unintended results.
htmlspecialcharsA PHP function that converts special HTML characters such as < and > into safe HTML entities, preventing cross-site scripting (XSS) when user-supplied data is output to a browser.
In class: Guided lab: students build a grade-reporting script that reads an associative array of student names and numeric scores, uses a function to assign letter grades, and outputs an HTML table — instructor circulates and checks logic before students run the script · Students use php.net to look up five array functions (array_map, array_filter, usort, array_slice, in_array) and write a short demonstration script for each, with comments explaining what the function does and why it is useful · Debug challenge: instructor provides three broken PHP files with errors in loop logic and function return values; students use error_reporting(E_ALL) output and hand-tracing to diagnose and fix each file, documenting the bug and fix in their lab log
Materials: PHP manual (php.net/manual/en/ref.array.php), VS Code, local PHP environment, instructor-provided broken PHP files, student lab log template
Check: Grade-reporting script produces correct letter grades and a valid HTML table for a provided test dataset of ten students; lab log entries for three debug challenges are complete and accurate — pass requires correct output and three complete log entries

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Programming concepts / control flow
1. A PHP `switch` statement is missing a `break` at the end of the first matching `case`. What will happen when that case matches?
Programming concepts / loops
2. Which PHP loop construct is most appropriate when iterating over every key-value pair in an associative array?
Programming concepts / functions and debugging
3. A student's `letterGrade()` function always returns 'F' even for scores above 90. What is the most likely cause?
Programming concepts / arrays
4. Which PHP built-in function would you use to keep only elements of an array that satisfy a custom condition, returning a new array containing just those elements?
Web security / output encoding
5. Why should `htmlspecialchars()` be applied to student names before they are echoed into an HTML table?
Programming concepts / debugging
6. A developer adds `error_reporting(E_ALL);` to the top of a PHP script. What is the primary benefit during debugging?
Programming concepts / functions
7. Which of the following correctly declares a PHP function that accepts an integer and returns a string?
Programming concepts / arrays
8. A student uses `array_map` to apply a callback to an array of numeric scores. Which statement best describes the result?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.