PrimitiveType

Create Alphabet Links With PHP

When a site has many sections or pages for a category, it can be useful to separate all entries by what letter of the alphabet their initial falls under. For example, you may want to do this in a directory site. It is a simple matter to create 26 HTML <a> tags to link to each page or section, but if you decide to change something about them you'd have to apply the edit to each of the 26 tags. Here is a very short PHP snippet that loops through the alphabet and echoes a tag for each letter:

for ($i = 65; $i <= 90; $i++) { printf('<a href="%1$s.html" class="myclass">%1$s</a> ', chr($i)); }

The code loops from 65 to 90 because that is the range of integers that defines the upper case English alphabet in ASCII codes. The function chr() is then used to convert each integer to its corresponding alphabet character. Finally, the function printf() is used to be able to use the output of chr() twice conveniently without calling the function more than once per letter or assigning it to a variable on each iteration of the loop. The notation %1$s means that the string value will be taken from the first argument after the string template.

The drawback to using this method to create links is that it isn't as fast to load as hard-coded HTML links (though in many cases the difference will be minute, you probably want to optimize your site anyway). You could always use the above snippet to make generating the links easier and then place the output in an HTML file for speedier downloads.

See Ascii Table for a list of all ASCII codes and their corresponding characters and symbols.