A first complete program: read commands, keep data, print a report.
What to build
A program that keeps a list of tasks.
Requirements
- Read lines until the input ends.
add TEXTadds a task (the text can have spaces).listprints the tasks as1. text,2. textand so on, or(empty)when there are none.
Input
Any number of command lines.
Output
The result of each list command.
Constraints
At most 100 lines; each task has at most 50 characters.
Example
Input:
add buy milk
add write code
list
Output:
1. buy milk
2. write code
Why it works
One array holds the data, and the loop turns each command into an action on it.
Examples
Example 1 · Input
add buy milk add write code list
Expected output
1. buy milk 2. write code
Example 2 · Input
list
Expected output
(empty)
Hints
Hint 1
Keep the tasks in an array and add with $tasks[] = $text.
Hint 2
For the text of a task, remove the first word of the line: substr($line, 4) after the word add and a space.
Solution
Show one correct solution (try it yourself first)
<?php
$tasks = [];
while (($line = fgets(STDIN)) !== false) {
$line = trim($line);
if (str_starts_with($line, "add ")) {
$tasks[] = substr($line, 4);
} elseif ($line === "list") {
if (count($tasks) === 0) {
echo "(empty)\n";
}
foreach ($tasks as $i => $task) {
echo $i + 1, ". ", $task, "\n";
}
}
}