Menu
CoddyTech

Memfilter berdasarkan Status Penyelesaian

Termasuk bagian Dasar-Dasar dalam perjalanan PHP di Coddy. Pelajaran 59 dari 71.

challenge icon

Tantangan

Mudah

Pada pelajaran sebelumnya, kamu menghapus tugas dari list. Sekarang, tambahkan kemampuan untuk memfilter tugas berdasarkan status penyelesaiannya.

Baca empat baris input untuk deskripsi tugas (tiga tugas awal ditambah satu tugas baru). Lalu, baca input kelima: bilangan bulat yang menunjukkan indeks tugas yang akan ditandai selesai. Baca input keenam: bilangan bulat yang menunjukkan indeks tugas yang akan dihapus. Terakhir, baca input ketujuh: string yang berupa completed atau pending untuk memfilter tugas.

Setelah membuat array $todos, menandai tugas yang ditentukan sebagai selesai, dan menghapus tugas pada indeks yang diberikan, filter tugas yang tersisa berdasarkan input filter:

  • Jika filternya adalah completed, tampilkan hanya tugas dengan "completed" bernilai true
  • Jika filternya adalah pending, tampilkan hanya tugas dengan "completed" bernilai false

Telusuri tugas yang tersisa dan cetak hanya tugas yang sesuai dengan filter, menggunakan format yang sama:

  • Jika tugas selesai: - [task description] (Done)
  • Jika tugas belum selesai: - [task description] (Pending)

Cetak setiap tugas yang cocok pada baris terpisah.

Contoh:

Jika inputnya adalah Buy groceries, Walk the dog, Finish homework, Call mom, 1, 2, dan completed, outputnya adalah:

- Walk the dog (Done)

Jika inputnya adalah Buy groceries, Walk the dog, Finish homework, Call mom, 1, 2, dan pending, outputnya adalah:

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

Coba sendiri

<?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";
    }
}
?>

Semua pelajaran di Dasar-Dasar

Latihan sendiri: Compiler PHP online