Tag: alphabet

Pesky Directory Alphabet Filters Made Easy (PHP)

I have built quite a few directory systems in my years as a web developer and one thing that has always annoyed me is building letter filters to return results depending on the first letter of a title.

Normally I would waste a lot of time actually typing out the entire alphabet string:

$alphabet = 'abcdefghijklmnopqrstuvwxyz';

which can take a lot of time (Go on try it, I’ll bet no matter how fast you can type, typing out the alphabet quickly will be tricky!) then looping through the string like so:

for($i = 0; $i < strlen($alphabet); $i++)
{
  echo substr($alphabet, $i, 1);
} 

However there are 2 other much simpler methods:

Method 1 – Loop through the ASCII numbers

for($i = 65; $i <= 90; $i++)
{
  echo chr($i);
}

or my new personal favourite using PHP’s range() function:

Method 2 – Using range()

foreach(range('A', 'Z') as $i)
{
  echo $i;
}

Then all you have to do is add in any code to make sure you set the right CSS selectors and highlight which letter you are currently viewing and add the ability to filter by first letter to your list function.

Simple.