Menu
Coddy logo textTech

Rimuovere un'attività

Fa parte della sezione Fondamenti del percorso PHP di Coddy. Lezione 58 di 71.

challenge icon

Sfida

Facile

Nella lezione precedente, hai contrassegnato un'attività come completata. Ora aggiungi la possibilità di rimuovere completamente un'attività dall'elenco.

Leggi quattro righe di input contenenti le descrizioni delle attività (tre attività iniziali più una nuova attività). Poi leggi un quinto input: un intero che rappresenta l'indice dell'attività da contrassegnare come completata. Infine, leggi un sesto input: un intero che rappresenta l'indice dell'attività da rimuovere dall'elenco.

Dopo aver creato l'array $todos con tutte e quattro le attività e aver contrassegnato l'attività specificata come completata, rimuovi l'attività all'indice di rimozione indicato usando array_splice().

La funzione array_splice() rimuove elementi da un array:

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

Poi esegui un ciclo sulle attività rimanenti e stampa ciascuna nello stesso formato di prima:

  • Se l'attività è completata: - [task description] (Done)
  • Se l'attività è in sospeso: - [task description] (Pending)

Stampa ogni attività su una riga separata.

Esempio:

Se gli input sono Buy groceries, Walk the dog, Finish homework, Call mom, 1 e 2, l'output dovrebbe essere:

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

Se gli input sono Clean room, Read book, Exercise, Cook dinner, 0 e 0, l'output dovrebbe essere:

- Read book (Pending)
- Exercise (Pending)
- Cook dinner (Pending)

Provalo tu

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

Tutte le lezioni di Fondamenti

Esercitati da solo: Compilatore PHP online