Nico Nico - 24 days ago 6
HTML Question

Getting x amount of items from array

I'm doing this task in school where I'm to do something with arrays and loops in PHP.

What I've done so far is make this piece of code, that makes an array with names from a separate text-file, and chooses a random name from that array.

What I'd like it to do now is to display x amount of random names. The amount of names can be chosen in an input field, preferably with a for or while loop (those are the ones I know somewhat).

Here is my code (Don't think the text-file is necessary. If it is, just let me know):

<form method="POST">
How many names do you need? <input type="number" name="amount" min="1" max="28"><br><br>
<input type="submit" name="proceed" value="Get name(s)">
</form>

<?php

$text = file_get_contents("names2t.txt");
$Array = explode("\n", $text);
$randNameNum = array_rand($Array);
$randPhrase = $Array[$randNameNum];

if (isset($_POST["proceed"])){
echo $randPhrase;
}


?>


Is it possible to do what I'm asking?

Thanks :-)

Answer

Just add another field on your form and loop on it :

    <form method="POST">
        How many names do you need?  <input type="number" name="amount" min="1" max="28"><br>
        How many times? <input type="number" name="repeat-count"><br>
        <input type="submit" name="proceed" value="Get name(s)">
     </form>

    <?php       

    if(isset($_POST['proceed'])) {
        for($i = 0; $i < $_POST['repeat-count']; $i++) {
            $text = file_get_contents("names2t.txt"); 
            $Array = explode("\n", $text); 
            $randNameNum = array_rand($Array); 
            echo $Array[$randNameNum]; 
        }
    }


     ?>