Sometimes you want to add a list of A-Z links to anchors on an existing page that is coming from a database. There are several solutions to this, the easiest being just to create all of those links by hand but this is needlessly tedious.
I came across the following code from an old project.
function oldatoz() // old function, pretty braindead, creates A-Z anchor links
for ($i=65; $i<=90; $i++)
$x = chr($i);
echo " | <a href=\"#$x\">$x</a>";
This gives us an orderly list listing all 26 letters of the alphabet. It's clever in that it uses very little code.
However this can become confusing if the page you have doesn't actually contain all these anchors. What if you want to exclude instances like #Z because there are no listings that start with a Z?
The answer is simple: we'll have to look it up and see what we actually need to use. This isn't too hard if you use
SELECT DISTINCT LEFT
function atoz() // new function, looks in the database for which starting letters are actually in use
$query = "SELECT DISTINCT LEFT(titel, 1) AS anchor FROM links ORDER BY anchor ASC";
$result = mysql_query($query);
while($abcd = mysql_fetch_array($result))
$linky = ucfirst($abcd); // be sleek, sexy and a slinky!
echo " | <a href='#$linky'>$linky</a>";
As you can see this creates a list of anchors that excludes certain items because they are not in use. Insert this function after every 10 records or so using something like
if ($j % 10 == 0) atoz();
The downside to this method is that it is inefficient but my database is fairly small and unlikely to grow to millions of records so it's an acceptable tradeoff.
Perhaps next time we'll look at creating the anchors automagically.