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

94

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

791

Answer

Solution:

$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.
743

Answer

Solution:

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

That is it in the least amount of code.

People are also looking for solutions to the problem: php - Isolate minimal portion of text based on search terms from user input

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.