Project: To-do list
Overview of the 5-lesson to-do project: manage tasks with arrays and functions.
Project: To-do list
In this 5-lesson project you'll build a to-do list. Each lesson adds one piece, and by the final lesson you'll have a complete working command-line app.
You'll use what you learned before:
- arrays to hold tasks
- associative arrays with
titleanddonekeys foreachto walk the list- function declarations and parameters
You'll also split the work into small functions (addTask, listTasks, completeTask) so the program looks like a real app. Ready? Let's start.
A quick refresher on arrays and functions
To create an array you use []: $tasks = []. To append a new element you write $tasks[] = ...; the element goes to the end.
A task has both a title and a completion flag. For that you use an associative array: ["title" => "Buy bread", "done" => false]. Here title holds the task name and done holds whether it is finished.
In this project every operation lives in a function: addTask adds a task, listTasks lists them, completeTask completes one. This way the code does not repeat and stays easy to read.
Exercise Add the first task
In this lesson you'll write the first piece of the project. Create an empty array called $tasks. Add the first task as an associative array with $tasks[] using ["title" => "Buy bread", "done" => false]. Then print Task count: 1 with echo, using count($tasks) and a \n at the end of the line.
Show example solution
An empty array is created with []; a task is appended as an associative array via $tasks[]. count($tasks) returns the number of elements.
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";
Test yourself
-
Why does a to-do list use functions?
- Because functions show the list in a browser
- Because they package repeating work (add, list, complete)
- Because functions store the array in a database
- Because functions auto-complete the tasks
Show answer
Because they package repeating work (add, list, complete) — Correct. Packaging operations like add, list and complete into functions keeps the code tidy and reusable.
-
Match each concept to its role
- array
- holds the tasks
- associative array
- title and done keys
- foreach
- walks the list
- function
- packages repeating work
-
Define an empty tasks array
$tasks ____;Show answer
$tasks = [];