Extend the task list with finishing and removing tasks, and with clear error messages.
What to build
A program that manages tasks.
Requirements
- Read lines until the input ends.
add TEXTadds a task that is not done.done Nmarks task number N as done.remove Nremoves it (later tasks move up one number).listprintsN. [ ] textfor open tasks,N. [x] textfor done tasks, or(empty). - When N is not the number of a task, print
no such task Nand change nothing.
Input
Any number of command lines.
Output
The result of list commands and error messages.
Constraints
At most 100 lines; each task has at most 50 characters; N is an integer.
Example
Input:
add wash car
add read book
done 1
list
Output:
1. [x] wash car
2. [ ] read book
Why it works
Keeping all rules in one structure makes the commands short, and the error check protects the list from bad numbers.
Examples
Example 1 · Input
add wash car add read book done 1 list
Expected output
1. [x] wash car 2. [ ] read book
Example 2 · Input
done 1 list
Expected output
no such task 1 (empty)
Hints
Hint 1
Store each task as an array with text and done, or keep two parallel arrays.
Hint 2
After remove, use array_values (or array_splice) so the numbers stay 1, 2, 3 without gaps.
Solution
Show one correct solution (try it yourself first)
<?php
$tasks = [];
while (($line = fgets(STDIN)) !== false) {
$line = trim($line);
$parts = explode(" ", $line, 2);
$cmd = $parts[0];
$arg = $parts[1] ?? "";
if ($cmd === "add") {
$tasks[] = ["text" => $arg, "done" => false];
} elseif ($cmd === "done" || $cmd === "remove") {
$index = (int) $arg - 1;
if (!isset($tasks[$index])) {
echo "no such task $arg\n";
} elseif ($cmd === "done") {
$tasks[$index]["done"] = true;
} else {
array_splice($tasks, $index, 1);
}
} elseif ($cmd === "list") {
if (count($tasks) === 0) {
echo "(empty)\n";
}
foreach ($tasks as $i => $task) {
echo $i + 1, ". ", $task["done"] ? "[x]" : "[ ]", " ", $task["text"], "\n";
}
}
}