PHP random quote generator
In this post, you will learn how to generate random quote in PHP programming language.
Some websites show random quotes to their visitors on different pages. This is generally used on websites like press releases, speech or news stories, as good quotes can help us enhance our credibility. It requires storing the contents of quotes either in an array or in a text file. Here, we have mentioned both ways of displaying a random quote.
PHP Random Quote Generator 1
Suppose we have a text file 'quotes.txt' that contains contexts of quotes.
Place the first quote
Place the second quote
Place the third quote
Place the fourth quote
Place the fivth quote
Place the sixth quote
The given code loads the contents of the file and arbitrarily shows a line from it. You can utilise this to show an arbitrary statement on a page each time it loads.
<?php
$file= "quotes.txt";
$quotes = file($file);
srand((double)microtime()*1000000);
$randomquote = rand(0, count($quotes)-1);
echo $quotes[$randomquote];
?>
Here is a sample output -
Place the second quote
PHP Random Quote Generator 2
In the given PHP code, we have stored the quotes in an array and used the rand() method to randomly display only one at a time. This code generates a random quote every time the page loads.
<?php
$quotes[] = 'Place the first quote ';
$quotes[] = 'Place the second quote';
$quotes[] = 'Place the third quote ';
$quotes[] = 'Place the fourth quote ';
$quotes[] = 'Place the fivth quote ';
srand ((double) microtime() * 1000000);
$random_number = rand(0,count($quotes)-1);
echo ($quotes[$random_number]);
?>
Related Articles
How to get data from XML file in PHPHow to lock a file using PHP
PHP remove last character from string
PHP code to send email using SMTP
Fibonacci series program
Import Excel File into MySQL using PHP
JavaScript display PDF in the browser using Ajax call
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP