How to echo random line from text file? [closed]

You can do this quite easily using the file and array_rand functions:

$lines = file($filename, FILE_IGNORE_NEW_LINES);
echo $lines[array_rand($lines)];
  1. file returns an array of all the lines of the file and stores it in $lines.
  2. array_rand picks a random index from the $lines array and the item at that index is echoed.

Leave a Comment