Menu
CoddyTech

Menghapus Tugas

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

challenge icon

Tantangan

Mudah

Di pelajaran sebelumnya, kamu menandai sebuah tugas sebagai selesai. Sekarang, tambahkan kemampuan untuk menghapus tugas sepenuhnya dari list.

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 sebagai selesai. Terakhir, baca input keenam: bilangan bulat yang menunjukkan indeks tugas yang akan dihapus dari list.

Setelah membuat array $todos yang berisi keempat tugas dan menandai tugas yang ditentukan sebagai selesai, hapus tugas pada indeks penghapusan yang diberikan menggunakan array_splice().

Fungsi array_splice() menghapus elemen dari array:

<?php
array_splice($array, $index, 1); // Removes 1 element at $index
?>

Lalu lakukan perulangan pada tugas yang tersisa dan cetak masing-masing dalam format yang sama seperti sebelumnya:

  • Jika tugas sudah selesai: - [task description] (Done)
  • Jika tugas masih tertunda: - [task description] (Pending)

Cetak setiap tugas pada baris terpisah.

Contoh:

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

- Buy groceries (Pending)
- Walk the dog (Done)
- Call mom (Pending)

Jika inputnya adalah Clean room, Read book, Exercise, Cook dinner, 0, dan 0, outputnya seharusnya:

- Read book (Pending)
- Exercise (Pending)
- Cook dinner (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));

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

// 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