Printing the alphabet in PHP

I was wondering of there was an smarter way to print the whole alphabet in PHP than just creating an array containing all off the letters by my self.

I present to you, the range() function.

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

This function will also work with numbers. This will print all the numbers from 1 to 12.

<?php
foreach(range(0, 12) as $number) {
    echo $number;
}
?>

And if you are smart, and run PHP 5, you can even print every tenth number (0,10,20,30...)

<?php
foreach(range(0, 100, 10) as $number) {
    echo $number;
}
?>
Tags:
Thanks!

Awesome tutorial. Didn't know about the Range function!

Submitted by Ian (not verified) on Thu, 08/16/2007 - 05:07.
so what?

so what?

Submitted by Anonymous (not verified) on Thu, 08/16/2007 - 23:08.
lol

lol

Submitted by Anonymous (not verified) on Mon, 08/20/2007 - 20:18.
An alternative

Or this:
array_walk(range('a', 'z'), "printf");

Submitted by Drew Vogel (not verified) on Wed, 08/22/2007 - 15:38.
<?php

<?php
for($i='a'; $i<'z'; $i++){
echo "$i";
}
echo "z";
?>

For some reason when I do "$i<='z'" it prints WAY out of range.

Submitted by Anonymous (not verified) on Wed, 08/22/2007 - 16:15.
Interesting

You can also use: Chr()

For UPPERCASE: for($i=65; $i<91; $i++) { echo chr($i); }

For lowercase: for($i=97; $i<123; $i++) { echo chr($i); }

Submitted by lazs_mccoy (not verified) on Mon, 10/01/2007 - 20:09.
Great tip

Wow that's impressive, really nice shortcut - big time saver as I would have assumed that I'd need another pesky loop to do this with numbers. Thanks, bookmarked this page for future reference. If only there was a way to increment the numbers by say +10

Submitted by Watch TV Online (not verified) on Fri, 03/14/2008 - 07:11.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><pre><blockquote>
  • Lines and paragraphs break automatically.
  • Insert Flickr images: [flickr-photo:id=230452326,size=s] or [flickr-photoset:id=72157594262419167,size=m].

More information about formatting options