Home > Software design >  Printing looped user input from an array PHP
Printing looped user input from an array PHP

Time:03-23

I'm making a small program that saves user input into an array an then prints the array, But I only get the last input printed each time. I'm using readline and php.eol because it has to work in the cmd.

<?php

echo "Hoeveel activiteiten wil je toevoegen?" . PHP_EOL;
$hoeveel = readline();
if (is_numeric($hoeveel)) {
    for ($i = 1; $i <= $hoeveel; $i  ) {
        echo "Wat wil je toevoegen aan je bucketlist?" . PHP_EOL;
        $entry *= $i;
        $entry = readline() . PHP_EOL;
        $bucketlist = array($entry, $entry, $entry);
    }
    echo "In jouw bucketlist staat: " . PHP_EOL;
    foreach ($bucketlist as $key) {
        echo $value;
    }
} else {
    exit($hoeveel . ' is geen getal, probeer het opnieuw');
}
?>

I've tried in it an associative array but it seems it should be possible in a normal array.

CodePudding user response:

You can store each value from readline() into $bucketlist and then loop the values from it.

  • Note that in your code there is no echo $value;
  • this part can be removed $entry *= $i; as it is immediately overwritten and it also does not exist yet

Example:

echo "Hoeveel activiteiten wil je toevoegen?" . PHP_EOL;
$hoeveel = readline();
$bucketlist = [];

if (is_numeric($hoeveel)) {
    for ($i = 1; $i <= $hoeveel; $i  ) {
        echo "Wat wil je toevoegen aan je bucketlist?" . PHP_EOL;
        $bucketlist[] = readline() . PHP_EOL;
    }
    echo "In jouw bucketlist staat: " . PHP_EOL;
    foreach ($bucketlist as $value) {
        echo $value;
    }
} else {
    exit($hoeveel . ' is geen getal, probeer het opnieuw');
}
  • Related