San
San

Reputation: 125

How to pick a random word from text file (array) using PHP?

How can I pick a random word from a file of comma-separated words?

Upvotes: 2

Views: 4443

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174957

$var = file_get_contents('the_file.txt'); //Take the contents from the file to the variable
$result = explode(',',$var); //Split it by ','
echo = $result[array_rand($result)]; //Return a random entry from the array.

Upvotes: 3

Chris
Chris

Reputation: 1579

echo explode(',',file_get_contents('file.txt'))[rand(0,99)];

That is it in the least amount of code.

Upvotes: 1

Related Questions