Technology Temerity

Quick Tip – Generating Alphabetical Link Lists

PHP

This article assumes LAMP stack or some other PHP-based web layout and basic proficiency with PHP scripting.

Imagine you’ve just finished one of those simple but massive and often tedious alphabetical link lists or tables all of us in the web business are called upon to assemble at some point. You know the customer will appreciate the convenience of anchors and bookmark links. On the surface it would appear you have the less than fun choices of cobbling together a cumbersome loop to generate your links, or to type and double check each one by hand. Fortunately as of PHP version 4.0 there is a better option: range().

PHP’s range() is an oft overlooked and very useful function that will accept two bookends and return an array containing the in between values in order (bookends included).

For an example, to get the set of letter bookmark links at the top of this page, we could do it the hard way:

<a href="#A">A</a>
<a href="#B">B</a>
<a href="#C">C</a>

We could also write some home grown functions, probably involving a nested loop or two. Assuming English characters, why do either when we could get the same result like this?

<?php
    $items = []; // List accumulator for HTML list items.
    $range = range('A', 'Z'); // Generate an array of letters from A to Z.

    // Scan through the range of letters and create a list item for each one.
    foreach ($range as $letter) {

        // Escape the letter for safe output in HTML.
        // Not necessary here, just good habit.
        $escaped = htmlspecialchars($letter, ENT_QUOTES, 'UTF-8');

        // Add a list item with a link to the 
        // corresponding section for this letter
        // and populate element.
        $items[] = sprintf(
            '<li><a href="#%s">%s</a></li>',
            $escaped,
            $escaped
        );
    }
?>

<!-- Output the navigation menu with the generated list items. -->
<nav aria-label="Alphabetical index">
    <ul class="alphabetical-index">
        <!-- Implode() joins the list items into a single string with newlines for readability. -->
        <?= implode("\n", $items) ?>
    </ul>
</nav>

Simple, elegant, reusable, and best of all it’s far less prone to human error. Either the whole list works or none of it will, in which case you will know right away without the need to check each link individually. Note this example requires 5.4+, but range() is available as of 4.0+.

Try your own experiments with range(). It’s not foolproof with all character sets and nothing you couldn’t do piecemeal or with custom solutions, but will often simplify and remove some human error from the workload.

Until next time!
DC

Author: Damon Caskey

Hello all, Damon Caskey here - the esteemed owner of this little slice of cyberspace. Welcome!

1 Comment

Leave a Reply