skip to Main Content

I know there are a lot of effective ways to do this, but I’d really like to know what’s wrong with this code.

for ($char = 'A'; $char <= 'Z'; $char++) {
    echo $char . "n";
}

This is the result I get

A
B
C
.
.
X
Y
Z
AA
AB
AC
AD
AE
AF
AG
AH
AI
AJ
..
..
..
YY
YZ

But we have tried to change in For

for ($char = 'A'; $char < 'Z'; $char++) {
    echo $char . "n";
}

I got this result

A
.
.
V
W
X
Y

3

Answers


  1. If you need to use increment operation on character variables, I’d recommend to follow the PHP example having for-loop to count iterations separately from alphabetic strings increments.

    $letter = 'A';
    for ($n=1; $n <= 26; $n++) 
    {
        echo $letter++ . PHP_EOL;
    }
    

    See PHP Example: https://www.php.net/manual/en/language.operators.increment.php

    If you looking for more efficient way of doing this, I would recommend looking into range() function, it’s really handy.

    Login or Signup to reply.
  2. $char <= 'Z'
    

    This is string comparison that compares 2 strings char by char. The rule is as same as the strcmp function in C. AA starts with A which is less than Z, so the loop doesn’t stop until ZZ which is longer than a single Z.

    Login or Signup to reply.
  3. The reason this is happening is because you used <= as the condition in your loop.

    When you increment a string containing letters, it wraps around from Z to AA and continues doing 2-character strings (after ZZ it will go to AAA, and so on). Since 'AA' <= 'Z' is true, the loop continues. It finally stops when it gets to YZ because ZA is more than Z.

    Changing the condition to < causes the loop to stop at Y, so it never reaches the end of the alphabet and doesn’t have a chance to wrap around.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search