Display A String By A Date Value With PHP

Printing off a random quote on a page is useful (or at least interesting), but it is nice to rotate them slower than every page view.

A better solution is to use a time based value to work out which quote to display. In this way the quote is changed every hour/day/week or whatever time period you have selected.

Create a file called quote.txt in the same directory as the script and put a single quote on each line.

quote 1
quote 2
quote 3

The following function will take a time part as a single parameter and return a quote.

function quoteByInterval($timePart){
 // Make sure it is a integer
 $timePart = intval($timePart);
 
 // Load the quotes file
 $quotes = file('quotes.txt');
 // How many quotes are there in the file?
 $quoteCount = count($quotes);
 
 // Figure out the posision of the quote
 $position = ($timePart % $quoteCount);
 
 // Return the quote
 return $quotes[$position];
}

To get the time parts you can use the PHP date() function with different parameters. Here are some examples.

echo date('z'); // produces the day of the year (0 to 365)
echo date('m'); // Month (1 to 12)
echo date('y'); // Year (currently 08)
echo date('W'); // Week (0 to 52)
echo date('G'); // Hour (0 to 23)
echo date('i'); // Minute (0 to 59)
echo date('s'); // Second (00 to 59)

To use the function just give it a date part, it will then figure out the rest. Here are some examples.

print quoteByInterval(date('i'));
print quoteByInterval(date('h'));
print quoteByInterval(date('y'));
print quoteByInterval(date('s'));

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
11 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.