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
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.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.
This is string comparison that compares 2 strings char by char. The rule is as same as the strcmp function in C.
AA
starts withA
which is less thanZ
, so the loop doesn’t stop untilZZ
which is longer than a singleZ
.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
toAA
and continues doing 2-character strings (afterZZ
it will go toAAA
, and so on). Since'AA' <= 'Z'
is true, the loop continues. It finally stops when it gets toYZ
becauseZA
is more thanZ
.Changing the condition to
<
causes the loop to stop atY
, so it never reaches the end of the alphabet and doesn’t have a chance to wrap around.