Listing tasks
Number and list tasks with foreach.
Listing the tasks
To print the tasks we use a foreach loop. When you write foreach ($tasks as $i => $task), PHP assigns the task's index to $i and the task itself to $task on each step.
The index starts at 0, but users want numbers starting from 1. So we shift it with ($i + 1). The task's title is reached with $task["title"].
We wrap the listing in a function and call it as listTasks($tasks); that way we can reuse it anywhere.
Line format and the done mark
We print each task line as 1. Buy bread [ ]. The mark in brackets shows the completion status: [ ] is pending, [x] is done.
We pick the mark based on $task["done"]. When if ($task["done"]) is true, the mark is [x]; otherwise it is [ ]. This way every call to the list shows the current state.
Exercise Write and call the listTasks function
Define the listTasks function with the signature function listTasks(array $tasks): void. In the body iterate with foreach ($tasks as $i => $task). For each task first set $mark = "[ ]"; if $task["done"] is true set $mark = "[x]". Then write echo ($i + 1) . ". " . $task["title"] . " " . $mark . "\n";. After the function call listTasks($tasks);. The output is three lines: 1. Buy bread [ ], 2. Buy milk [ ], 3. Take out trash [ ].
Show example solution
function listTasks(array $tasks): void. Body: foreach ($tasks as $i => $task) { $mark = "[ ]"; if ($task["done"]) { $mark = "[x]"; } echo ($i + 1) . ". " . $task["title"] . " " . $mark . "\n"; }. Then listTasks($tasks);.
Example solution:
<?php
// Initialize the tasks array and add the first task
$tasks = [];
$tasks[] = ["title" => "Buy bread", "done" => false];
echo "Task count: " . count($tasks) . "\n";
// Define the addTask function and add two more tasks
function addTask(array $tasks, string $title): array {
$tasks[] = ["title" => $title, "done" => false];
return $tasks;
}
$tasks = addTask($tasks, "Buy milk");
$tasks = addTask($tasks, "Take out trash");
echo "Task count: " . count($tasks) . "\n";
// Write and call the listTasks function
function listTasks(array $tasks): void {
foreach ($tasks as $i => $task) {
$mark = "[ ]";
if ($task["done"]) {
$mark = "[x]";
}
echo ($i + 1) . ". " . $task["title"] . " " . $mark . "\n";
}
}
listTasks($tasks);
Test yourself
-
In foreach ($tasks as $i => $task), what is $i?
- The task's index in the array (starts at 0)
- The task's title
- The task's done value
- The total length of the array
Show answer
The task's index in the array (starts at 0) — Correct. $i is the index that gives the position; it is 0 for the first task.
-
Complete the foreach header
foreach ($tasks as ____) { echo $task["title"]; }Show answer
foreach ($tasks as $i => $task) { echo $task["title"]; } -
Match the foreach parts
- foreach
- walks the array
- as $i => $task
- gives index and value
- $task["title"]
- the task title
- ($i + 1)
- number starting from 1