Get random word from English dictionary in PHP tutorial

Now, we are going to see a nice PHP tutorial and hoping that it will be so interesting to all. In this tutorial, we are going to get and then show random English word from the English dictionary which really going to be interesting.

How are we going to do that?

In this tutorial, we are going to use a text file “words_alpha.txt” which contains the English words one per line. From that file, we are going to choose a random line and then from that line, we are going to get the word. Thus, a random English word will appear every time we rin our code.

Get random text by line number from a text file in PHP

You may ask, how we got the text file. Well, we have just download it from GitHub. You can also download it or any other text file from the internet that contains English dictionary words.

We already have a tutorial – Get random text by line number from a text file in PHP. In this post, we show the code how to get a random text by random line number. We are going to apply the same procedure here in this tutorial. We will first make an array of the text file and choose the random index or line number. From that number of line, we will get the text and display it on the web page.



Below is the given code of this tutorial:

<?php
$file = "words_alpha.txt";
// Convert the text fle into array and get text of each line in each array index
$file_arr = file($file);
// Total number of lines in file
$num_lines = count($file_arr);
// Getting the last array index number
$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 have some comment that describes you our steps.

After we get the last array index we just have to get a random index number from 0 to last index number. Also, you can notice that we have subtracted 1 from the total number of lines to get the last array index. This is because the number of lines we count from the array starts from 1 and the index number starts from 0. So we subtract 1 from the total number of lines.

How To Generate Random Password In PHP?

Get visitors country and city in PHP using Freegeoip API

After that, we use PHP rand() function to get the random index number of the array of the text file. Though we are saying random line number, we are actually choosing the random index number as we are now working with an array which contains the text of each line of the text file in an array index. In the end, we are getting the text of that line by choosing the random index number.

That’s it. We are able to get and display a random word from English dictionary or from English words.

Leave a Reply

Your email address will not be published. Required fields are marked *