Menu
Coddy logo textTech

Filtering by Completion Status

Part of the Fundamentals section of Coddy's PHP journey — lesson 59 of 71.

challenge icon

Challenge

Easy

In the previous lesson, you removed a task from the list. Now, add the ability to filter tasks by their completion status.

Read four lines of input for task descriptions (three initial tasks plus one new task). Then read a fifth input: an integer representing the index of the task to mark as complete. Read a sixth input: an integer representing the index of the task to remove. Finally, read a seventh input: a string that is either completed or pending to filter the tasks.

After building the $todos array, marking the specified task as complete, and removing the task at the given index, filter the remaining tasks based on the filter input:

  • If the filter is completed, display only tasks where "completed" is true
  • If the filter is pending, display only tasks where "completed" is false

Loop through the remaining tasks and print only the ones that match the filter, using the same format:

  • If the task is completed: - [task description] (Done)
  • If the task is pending: - [task description] (Pending)

Print each matching task on a separate line.

Example:

If the inputs are Buy groceries, Walk the dog, Finish homework, Call mom, 1, 2, and completed, the output should be:

- Walk the dog (Done)

If the inputs are Buy groceries, Walk the dog, Finish homework, Call mom, 1, 2, and pending, the output should be:

- Buy groceries (Pending)
- Call mom (Pending)

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));

// Read the index of the task to mark as complete
$completeIndex = (int)trim(fgets(STDIN));

// Read the index of the task to remove
$removeIndex = (int)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];

// Mark the task at the specified index as complete
$todos[$completeIndex]["completed"] = true;

// Remove the task at the specified removal index
array_splice($todos, $removeIndex, 1);

// Loop through the array and print each task in the formatted list
foreach ($todos as $todo) {
    if ($todo["completed"]) {
        echo "- " . $todo["task"] . " (Done)\n";
    } else {
        echo "- " . $todo["task"] . " (Pending)\n";
    }
}
?>

All lessons in Fundamentals