PHP: List URLs by Day

A recent problem arose when trying to provide a dynamic list of linked URLs on a page based on the textual name rather than the the numeric date. A number of sub-pages on a website has unique but not ordered URLs, suffixed with a page number (numeric).

The problem was compounded by the fact that the target links, while part of the same site, where not in ascending order. And obviously it would be nicer if we start with today and work forwards.

This is what we started with:

  • Monday (which points to 39)
  • Tuesday (which points to 40)
  • Wednesday (which points to 38)
  • Thursday (which points to 41)
  • Friday (which points to 42)
  • Saturday (which points to 36)
  • Sunday (which points to 37)
  • Today (which points to 35)

We actually want:

  • Today
  • Tomorrow
  • The day after that
  • The day after that
  • The day after that and
  • The last day

And we also want to include the date for the day listed as well so it’s clear what day it refers to.

The trick used was to create an array of days, indexed by the day name (e.g. Monday), and then work forward in a fixed loop using the PHP date function, to determine the real day name and date. We use the PHP strtotime function with a string that says it is one or more days ahead, which returns the date which in turn allows the date function to correctly return the textual day name. So we get the actual date (e.g. Jun 26), we do that as well using the same method. Once we have both results, glue them together as the visual representation of the HTML link (the mark-up).

Note that “today” and “tomorrow” are separate from the remainder of the loop, because the suffix is slightly different. But you could lump them all together.

The end result looks like this:

// create an array for the days of the week, with the
//  pointer a textual day name
$week = array( "Monday"=>39, "Tuesday"=>40, "Wednesday"=>38,
    "Thursday"=>41, "Friday"=>42, "Saturday"=>36, "Sunday"=>37,
    "Today"=>35 ); 

$dayname = date('l', strtotime('today'));
echo ''.$dayname.
    ' Today - 4Km';
$dayname = date('l', strtotime('+1 day'));
$daydate = date('d M', strtotime('+1 day'));
echo '
'.$dayname. ' '.$daydate.' - 5Km'; for ($day = 2; $day < 7; $day++ ) { $dayname = date('l', strtotime('+'.$day.' day')); echo '
'; echo $dayname; $daydate = date('d M', strtotime('+'.$day.' day')); echo ' '.$daydate; echo ' - 12Km'; }

And the actual output looks like this when today is “Sunday” and the 26th of June:

  • Sunday Today – 4Km
  • Monday 27 Jun – 5Km
  • Tuesday 28 Jun – 12Km
  • Wednesday 29 Jun – 12Km
  • Thursday 30 Jun – 12Km
  • Friday 01 Jul – 12Km
  • Saturday 02 Jul – 12Km

Note that this isn’t showing the embedded HTML links, but you should get the idea.

One thought on “PHP: List URLs by Day

  1. Pingback: Stratus

Comments are closed.