Jump to content

Word Generator that Doesn't Repeat


LivingReceiver

Recommended Posts

Hello Everyone!

 

I was just wondering if anyone knew how to code a word generator that will give an three outputs without repeating any of the words.

 

I want to make three radio buttons that have a random generated word from a list of words I created, but none of the words can repeat.

 

I have the list of the words on a text file, and this is the code I am currently using. (All I did was repeat it three times to get the three outputs, but when I tested it I have had times where it repeats the same word three times.)

 

<?php
$filename="words.txt";
$words=file($filename);
shuffle($words);
$word=$words[0];
echo $word;
?>

 

Any ideas? Thanks!

Link to comment
Share on other sites

You almost have it. I'm guessing you are running that same block of code three times which is like picking a card out of a hat, putting the card back, and picking another card. You need to pick three words without starting over. After you shuffle all the words to randomize them you just need to pick the top three records.

 

$filename="words.txt";
$words=file($filename);
shuffle($words);

$randomWords = array_slice($words, 0, 3);
echo "<pre>" . print_r($randomWords, true) . "</pre>";

// Or
echo $randomWords[0];
echo $randomWords[1];
echo $randomWords[2];

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.