タスクの削除
CoddyのPHPジャーニー「基礎」セクションの一部 — レッスン 58/71。
チャレンジ
簡単前のレッスンでは、タスクを完了としてマークしました。今度は、リストからタスクを完全に削除する機能を追加します。
タスクの説明のための4行の入力を読み込みます(3つの初期タスクと1つの新しいタスク)。次に5番目の入力として、完了としてマークするタスクのインデックスを表す整数を読み込みます。最後に6番目の入力として、リストから削除するタスクのインデックスを表す整数を読み込みます。
すべての4つのタスクで$todos配列を構築し、指定されたタスクを完了としてマークした後、array_splice()を使用して指定された削除インデックスのタスクを削除します。
array_splice()関数は配列から要素を削除します:
<?php
array_splice($array, $index, 1); // Removes 1 element at $index
?>次に、残りのタスクをループし、各タスクを以前と同じ形式で印刷します:
- タスクが完了している場合:
- [task description] (Done) - タスクが保留中の場合:
- [task description] (Pending)
各タスクを別々の行に印刷します。
例:
入力がBuy groceries、Walk the dog、Finish homework、Call mom、1、2の場合、出力は次のようになります:
- Buy groceries (Pending)
- Walk the dog (Done)
- Call mom (Pending)入力がClean room、Read book、Exercise、Cook dinner、0、0の場合、出力は次のようになります:
- Read book (Pending)
- Exercise (Pending)
- Cook dinner (Pending)自分で試してみよう
<?php
// タスクのコレクション
$tasks = [
[
"description" => "Buy groceries",
"completed" => false
],
[
"description" => "Walk the dog",
"completed" => true
],
[
"description" => "Read a book",
"completed" => false
],
[
"description" => "Exercise",
"completed" => true
],
[
"description" => "Clean house",
"completed" => false
]
];
// 入力の読み取り
$taskIndex = trim(fgets(STDIN));
// TODO: ここにコードを書いてください
// タスクインデックスを整数に変換
// unset() を使用してタスクを削除
// array_values() を使用して配列を再インデックス
// 削除されたタスクと残りのタスクを表示
?>基礎のすべてのレッスン
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 Types3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators