Marking a Task as Complete
Part of the Fundamentals section of Coddy's PHP journey — lesson 57 of 71.
Challenge
EasyIn the previous lesson, you displayed all tasks with their status. Now, add the ability to mark a specific task as complete.
Read four lines of input for task descriptions (three initial tasks plus one new task, as before). Then read a fifth input: an integer representing the index of the task to mark as complete (0-based).
After building the $todos array with all four tasks, update the "completed" value to true for the task at the specified index.
Then loop through the array and print each task in the following format:
- If the task is completed:
- [task description] (Done) - If the task is pending:
- [task description] (Pending)
Print each task on a separate line.
Example:
If the inputs are Buy groceries, Walk the dog, Finish homework, Call mom, and 1, the output should be:
- Buy groceries (Pending)
- Walk the dog (Done)
- Finish homework (Pending)
- Call mom (Pending)If the inputs are Clean room, Read book, Exercise, Cook dinner, and 3, the output should be:
- Clean room (Pending)
- Read book (Pending)
- Exercise (Pending)
- Cook dinner (Done)Try it yourself
<?php
// Read three task descriptions
$task1 = trim(fgets(STDIN));
$task2 = trim(fgets(STDIN));
$task3 = trim(fgets(STDIN));
// Read the new task to add
$newTask = trim(fgets(STDIN));
// Create a $todos array containing three task arrays
// Each task should be an associative array with "task" and "completed" keys
$todos = [
["task" => $task1, "completed" => false],
["task" => $task2, "completed" => false],
["task" => $task3, "completed" => false]
];
// Add the new task to the end of the array
$todos[] = ["task" => $newTask, "completed" => false];
// Loop through the array and print each task in the formatted list
foreach ($todos as $todo) {
echo "- " . $todo["task"] . " (Pending)\n";
}
?>All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators6Arrays Part 1 - Indexed
Introduction to ArraysCreating Indexed ArraysAccessing Elements by IndexModifying Elements by IndexArray Size with CountAdding Elements to an ArrayRecap - Managing a Simple List9Project: Simple To-Do List
Project Overview & DataAdding a New Task