Get random text by line number from a text file in PHP
Here in this tutorial, we are going to play with PHP and a text file. the text file is of multiple lines and each of the lines contains some text. Now we are going to choose a line number in a random way and from that line number we are going to get the text.
In this way, we can show a random word or random text very easily just from a text file.
Suppose, we have a text file “colors.txt” which is of 5 lines and the content of the text file is given below:
Red Green Blue Yellow Pink
As you can see, the text file “colors.txt” contains with five colors, one in each line. Now we are going to choose a random line and get the text from that line.
below is the PHP code which will do this task:
<?php $file = "colors.txt"; // Convert the text fle into array and get text of each line in each array index $file_arr = file($file); // Total number of linesin file $num_lines = count($file_arr); // Getting the last array index number by subtracting 1 as the array index starts from 0 $last_arr_index = $num_lines - 1; // Random index number $rand_index = rand(0, $last_arr_index); // random text from a line. The line will be a random number within the indexes of the array $rand_text = $file_arr[$rand_index]; echo $rand_text; ?>
In the above code, we can read each line so that we can understand what we have done and for which purpose. We can see that the text of each line come in an array and the text of each line is in an array index. We can see that the array index starts from 0 and the count of index starts from 1. So, to get a random line number we have to choose the random array index. For this reason, we have subtracted 1 from the total number of lines in the text file.
After that, we have used PHP rand() function to get the text from a random line number. Actually, it is better to say to choose a random array index than line number as we are here getting a random text by choosing random array index.
So, we did it. Now every time we run our code, we will get a random text from a particular line of “colors.txt” text file.