This is a website by Willem van Zyl

I'm a project manager, software developer, Apple evangelist and geek from South Africa. I'm passionate about web and mobile application development, usability, productivity, physics, astronomy, science fiction and fantasy.

If you would like to contact me, message me on Twitter or send me an email.

Alphabetical "for" and "foreach" loops in PHP

26 Jan 2009

By combining a for loop with PHP's chr() function you can create a loop that will run through each letter of the alphabet:

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

An easier way to loop through each letter of the alphabet (or each value of any range therein), is to use PHP's range() function in combination with a foreach loop:

<?php
  foreach (range('a', 'z') as $i)
  {
    echo $i;
  }
?>

You can even use the range() function to loop through the letters in reverse alphabetical order:

<?php
  foreach (range('g', 'b') as $i)
  {
    echo $i;
  }
?>
Do you like this? Share it:

Copyright © Geekology 2011. All Rights Reserved.

Hosted by Code. Like. Clockwork.