Menu
Coddy logo textTech

Adding a New Task

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

challenge icon

Challenge

Easy

In the previous lesson, you created a $todos array with three initial tasks. Now, add the ability to insert a new task into the list.

Read three lines of input for the initial task descriptions, then read a fourth line containing a new task to add.

After creating the initial $todos array with three tasks (each having "task" and "completed" keys), add the new task to the end of the array. The new task should also have "completed" set to false.

Then print:

  1. The total number of tasks after adding the new one
  2. The task description of the last task in the list (the one you just added)

Print each result on a separate line.

Example:

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

4
Call mom

If the inputs are Clean room, Read book, Exercise, and Cook dinner, the output should be:

4
Cook dinner

Try it yourself

<?php
// Read three task descriptions
$task1 = trim(fgets(STDIN));
$task2 = trim(fgets(STDIN));
$task3 = trim(fgets(STDIN));

// TODO: Write your code below
// 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]
];

// Output the first task description
echo $todos[0]["task"] . "\n";

// Output the second task description
echo $todos[1]["task"] . "\n";

// Output the total number of tasks
echo count($todos);
?>

All lessons in Fundamentals