Friday, 10 August 2018

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.
  1. quote 1
  2. quote 2
  3. quote 3
The following function will take a time part as a single parameter and return a quote.
  1. function quoteByInterval($timePart){
  2. // Make sure it is a integer
  3. $timePart = intval($timePart);
  4.  
  5. // Load the quotes file
  6. $quotes = file('quotes.txt');
  7. // How many quotes are there in the file?
  8. $quoteCount = count($quotes);
  9.  
  10. // Figure out the posision of the quote
  11. $position = ($timePart % $quoteCount);
  12.  
  13. // Return the quote
  14. return $quotes[$position];
  15. }
To get the time parts you can use the PHP date() function with different parameters. Here are some examples.
  1. echo date('z'); // produces the day of the year (0 to 365)
  2. echo date('m'); // Month (1 to 12)
  3. echo date('y'); // Year (currently 08)
  4. echo date('W'); // Week (0 to 52)
  5. echo date('G'); // Hour (0 to 23)
  6. echo date('i'); // Minute (0 to 59)
  7. 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.
  1. print quoteByInterval(date('i'));
  2. print quoteByInterval(date('h'));
  3. print quoteByInterval(date('y'));
  4. print quoteByInterval(date('s'));

0 comments:

Post a Comment