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
https://forums.phpfreaks.com/topic/273564-word-generator-that-doesnt-repeat/
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];

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.