Printing the alphabet in PHP
Submitted by xqus on Sun, 08/05/2007 - 23:10
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;
}
?>
Awesome tutorial. Didn't know about the Range function!
- reply
Submitted by Ian (not verified) on Thu, 08/16/2007 - 05:07.so what?
- reply
Submitted by Anonymous (not verified) on Thu, 08/16/2007 - 23:08.lol
- reply
Submitted by Anonymous (not verified) on Mon, 08/20/2007 - 20:18.Or this:
array_walk(range('a', 'z'), "printf");
- reply
Submitted by Drew Vogel (not verified) on Wed, 08/22/2007 - 15:38.<?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.
- reply
Submitted by Anonymous (not verified) on Wed, 08/22/2007 - 16:15.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); }
- reply
Submitted by lazs_mccoy (not verified) on Mon, 10/01/2007 - 20:09.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
- reply
Submitted by Watch TV Online (not verified) on Fri, 03/14/2008 - 07:11.the third optional argument of the range function allows you to specify the step number,
so... range(0,100,10) will print 0,10,20...100
- reply
Submitted by Ken (not verified) on Mon, 07/20/2009 - 01:11.Thank you. this is great. Just the thing I have been looking for...
- reply
Submitted by Krishan (not verified) on Thu, 01/01/2009 - 11:38.echo join(' ', range( 'a', 'z' ) );
- reply
Submitted by Travis Ballard (not verified) on Tue, 03/03/2009 - 05:17.Awesome tut ..... never know this before ..... many thanks for sharing
- reply
Submitted by ny web design (not verified) on Sat, 04/11/2009 - 10:40.you can also use a for like this:
for ($k='a';$k<='z';$k++)
echo $k;
- reply
Submitted by Codes Tips (not verified) on Mon, 06/01/2009 - 19:12.Thanks for the Tip!
I found you through Stumble. Giving you a Thumbs Up!
Thanks
- reply
Submitted by ontario traffic ticket (not verified) on Wed, 06/03/2009 - 13:13.Post new comment