439
<?php
for ($i = 'a'; $i <= 'z'; $i++)
    echo "$i\n";

This snippet gives the following output (newlines are replaced by spaces):

a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev ew ex... on to yz

7
  • 32
    PHP is not C, even if the syntax tries to convince you of the contrary.
    – joni
    Nov 4, 2010 at 15:40
  • 3
    This works for me with a very small change: for ($i = 'a'; $i != 'aa'; $i++) { echo "$i\n"; } Nov 4, 2010 at 15:43
  • 2
    The comment about that PHP is not C - was the most keenest, example: in c: char c = 'a'; is not the same as in php: $c = 'a';, the point is that in C there is type of char(character 1 symbol), but not in PHP, if U tell PHP $c = 'a'; - means this is a string with just 1 character. That's why U can't loop through 28 characters adequately in PHP. I hope every programmer will learn low-level languages and strong-typing along with it, without forgetting about Math practices, which will help them to be stronger. Oct 15, 2012 at 19:26
  • Wow that is really cool, But why it didnt stopped at "z" Feb 7, 2013 at 8:41
  • For a way of getting the expected end-point by using equality (== or !=) check out this answer to a related question.
    – IMSoP
    Sep 23, 2013 at 20:11

16 Answers 16

342

From the docs:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's.

For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ).

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

From Comments:-
It should also be noted that <= is a lexicographical comparison, so 'z'+1 ≤ 'z'. (Since 'z'+1 = 'aa' ≤ 'z'. But 'za' ≤ 'z' is the first time the comparison is false.) Breaking when $i == 'z' would work, for instance.

Example here.

6
  • Hah..that's crazy! I've always used ord() so I never noticed this.
    – mpen
    Nov 4, 2010 at 16:52
  • 68
    For completeness, you should also add that "<=" is lexicographical comparison, so 'z'+1 ≤ 'z'. (Since 'z'+1='aa'≤'z'. But 'zz'≤'z' is the first time the comparison is false.) Breaking when $i=='z' would work, for instance. Nov 4, 2010 at 17:53
  • 6
    as ShreevatsaR is saying, it's the comparator, not the arithmetic that's the trouble, don't focus on the ++ operator
    – slf
    Nov 4, 2010 at 18:49
  • 10
    @ShreevatsaR: actually, 'yz'+1 = 'za'. The first comparison that fails is 'za'<='z' Nov 4, 2010 at 20:48
  • 2
    Thanks for the comments guys! Yeah, the key point is that 'aa' is lexicographically smaller than 'z', that's why the loop continues. And it stops on 'yz' because 'za' is greater than z. Check this example. Nov 6, 2010 at 2:06
124

Because once 'z' is reached (and this is a valid result within your range, the $i++ increments it to the next value in sequence), the next value will be 'aa'; and alphabetically, 'aa' is < 'z', so the comparison is never met

for ($i = 'a'; $i != 'aa'; $i++) 
    echo "$i\n"; 
12
  • 55
    It is odd that 'z'++ = 'aa', but 'aa' < 'z'. That logic doesn't flow very well. Nov 4, 2010 at 15:47
  • 19
    @Matthew: Alphabetize them. 'aa' would come first, thus it's "less than" the string 'z'. The loop terminates at 'zz' because it's alphabetically "greater than" (comes after) 'z'. It's illogical in the sense that you can "increment" something and get a lesser value, but it's logical in an alphabetical sense. Nov 4, 2010 at 15:48
  • 2
    The character incrementor is Perl logic (see CMS's quote from the docs). The comparison 'aa' < 'z' is standard string comparison logic. Not odd, once you understand how to use it... from the answers here, a lot of people don't.
    – Mark Baker
    Nov 4, 2010 at 15:49
  • 5
    @eldarerathis Oh I definitely understand how it is working. I just find it odd at the same time. Nov 4, 2010 at 15:50
  • 2
    It's incredibly useful for me, playing around with Excel columns that follow the same logical series
    – Mark Baker
    Nov 4, 2010 at 15:52
97

Others answers explain the observed behavior of the posted code. Here is one way to do what you want (and it's cleaner code, IMO):

foreach (range('a', 'z') as $i)
    echo "$i\n";

In response to ShreevatsaR's comment/question about the range function: Yes, it produces the "right endpoint", i.e. the values passed to the function are in the range. To illustrate, the output from the above code was:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
4
  • 2
    Does range() include the right endpoint? From experience with other languages, that's unexpected too! Nov 4, 2010 at 17:54
  • 1
    @ShreevatsaR: Yes, range() gives the "right" endpoint, see my edited answer (and follow the link to the function) for more info.
    – GreenMatt
    Nov 4, 2010 at 18:18
  • 1
    What can I say… more PHP madness. :-) There's no other language I know of in which range() works this way. (Certainly not, say, Haskell or Python.) Didn't Dijkstra write something about this? Nov 5, 2010 at 4:22
  • 10
    Madness is in the inconsistency of PHP. range('A','CZ') works totally differently to the ++ incrementor, and the resulting array will just contain three values: A, B and C.
    – Mark Baker
    Nov 5, 2010 at 9:00
35

Others already said why PHP doesn't show what you expect. Here's how you get the result you might want:

<?php
for ($i = ord('a'); $i <= ord('z'); $i++)
    echo chr($i);
?>
3
  • 2
    Unnecessary. you don't need to do the ord() at all, just the correct comparison to terminate the loop
    – Mark Baker
    Nov 4, 2010 at 15:46
  • 2
    +1 Much more comprehensible when not familiar with one of the more eccentric features of PHP. Nov 4, 2010 at 17:41
  • 2
    This is an excellent example of self-documenting code. It is easily comprehensible precisely b/c it uses ordinal values and then displays the variable as a character. The for-loop would be more efficient if the test for the maximum value is determined only once as follows: "for ($i = ord('a'),$max = ord('z'); $i <= $max; $i++){"
    – slevy1
    Dec 1, 2014 at 0:15
22

Why not just use range('a','z')?

4

Try this code. I think this code will be helpful to you.

$alphas = range('A', 'Z');
foreach($alphas as $value){
    echo $value."<br>";
}

Display 26 letters in sequence.

3

PHP has the function of looping letters and can exceed beyond single characters; the rest will be done this way: aa ab ac... zz, and so on.

Try this:

<?php
for ($i = 'a'; $i !== 'aa'; $i++)
    echo "$i\n";
?>
2
<?php

$i = 'a';
do {
echo ($j=$i++),"\r\n";
} while (ord($j) < ord($i));

?>
2

Also this can be used:

for ($i = 'a'; $i <= 'z'; $i=chr(ord($i)+1))
    echo "$i\n";
0

While the above answers are insightful to what's going on, and pretty interesting (I didn't know it would behave like this, and its good to see why.

The easiest fix (although perhaps not the most meaningful) would be just to change the condition to $i != 'z'

<?php
for ($i = 'a'; $i != 'z'; $i++)  
    echo "$i\n";
?>
2
  • 4
    Note that this will only give you a to y, not z
    – Mark Baker
    Nov 4, 2010 at 16:41
  • doh! yep, good point. I can see the logic behind both the increment and the comparison, but it sure is strange that sometimes $a++ < $a Nov 4, 2010 at 18:07
0

The PHP does not consider 'AA' less than 'Z'. The best way to make this is:

for($i = 'a'; $i != 'aa'; $i++) {
  echo $i;
}

abcdefghijklmnopqrstuvwxyz

0

Perhaps this code will work. It’s easy & can be understood:

<?php
$ascii_val = ord("a");
for($i=$ascii_val;$i<$ascii_val+26;$i++){
echo chr($i)."\n";
}
?>

where 26 is the total number of letters in the alphabet.

0

There are several ways to do that.

1. First you can take the range from 'a' to 'z'. Then iterate a loop over it.

foreach(range('a', 'z') as $i)
{
    echo $i . "\n";
}

2. You can print the letters using asci value of the characters.

for($i = 97 ; $i<=122; $i++)
{
  echo chr($i) . "\n";
}

3. You can take the asci value of 'a' and run a loop till the asci value of 'z':

for ($x = ord('a'); $x <= ord('z'); $x++)
{
    echo chr($x) . "\n";
}

4. For printing a new line in html you can append the
to the end of each characters.

for($i='a';$i<='z';$i++)
{
    echo $i. "<br />"; 
}
0

this code will work. It’s easy & can be understood:

<?php


// print form A to ZZ  like this
// A B C ... AA AB AC ... ZA .. ZZ
$pre = "";
$i = ord('a');
for ($x = ord('a'); $pre . strtoupper(chr($x-1)) != 'AH'; $x++)
{
    echo "". $pre . strtoupper(chr($x)) . "\n";

    if(chr($x) === "z"){
        $pre = strtoupper(chr($i++));
        $x = ord('a');
        $x--;
    }
}
0

One more way to get the display of characters a-z:

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

See live code Once the conditional loop becomes false, $i will have already been incremented and have the string value corresponding to 'z' which can be displayed.

-3

Wow I really didn't know about this but its not a big code you can try echo "z" after loop Mark is Absolutely Right I use his method but if you want alternative then this may also you can try

<?php
for ($i = "a"; $i = "y"; $i++) {
    echo "$i\n";
    if ($i == "z") {}
}
echo "z";
?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.