Loop through the Alphabet with PHP

  • Difficulty: Easy
  • Snippet Length: 1 minute
  • Technologies: PHP, HTML

I have several times wanted to provide a client with a facility to filter data by an alphabetic character and have done so by manually typing each letter of the alphabet with a hard link for example.

Old Way

A | B | C | D | E | F | G | H |


Short & Sweet way

I realised that I can use PHP's inbuilt chr function to echo out the relevant ASCII character, the capitalised alphabetic sequence starts from 65 so by just incrementing until 90 will give us all of our desired chars.

Let's try it out

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

Adding a little markup

// Loop through ASCII characters until reaching 90
for ($i=65; $i<=90; $i++) {	
	// store the character
	$letter = chr($i);

	// build alphabetical link
	$alphabet .= '<a title="filter results by letter '.$letter.'" href="/business/'.$letter.'"> ';
	$alphabet .= $letter;
	$alphabet .= '</a> | '; 

// print links
echo $alphabet;

comments powered by Disqus