Adding a New Task
Part of the Fundamentals section of Coddy's PHP journey — lesson 55 of 71.
Challenge
EasyIn 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:
- The total number of tasks after adding the new one
- 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 momIf the inputs are Clean room, Read book, Exercise, and Cook dinner, the output should be:
4
Cook dinnerTry 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
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