Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list from A to Z in PHP, and then on to AA, AB, AC, etc [duplicate]

Tags:

php

I know how to list from A to Z:

foreach (range('A', 'Z') as $char) {
  echo $char . "\n";
}

But how do I go on from there to list AA, AB, AC, AD, ... AZ, BA, BB, BC and so on?

I did a quick Google search and couldn't find anything, though I guess the approach will be different.

I think I can do it by using a for loop and an array with the letters inside, though that way seems a bit uncouth.

Any other way?

Thanks.

like image 311
Lucas Avatar asked Sep 21 '14 11:09

Lucas


3 Answers

PHP has the string increment operator that does exactly that:

for($x = 'A'; $x < 'ZZ'; $x++)
    echo $x, ' ';

Result:

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... 

Ref:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

http://php.net/manual/en/language.operators.increment.php

like image 159
georg Avatar answered Nov 08 '22 10:11

georg


Try

foreach (range('A', 'Z') as $char) {
    foreach (range('A', 'Z') as $char1) {
        echo $char . $char1. "\n";
    }
}
like image 36
Zeusarm Avatar answered Nov 08 '22 09:11

Zeusarm


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

Hence it is possible to increment alphabets in php

$limit = "AZ";

for($x = "A", $limit++; $x != $limit; $x++) {

    echo "$x ";

}

will give you result

A
B
C
.
.
.
AX
AY
AZ

Hope this will help.

like image 1
Shailesh Sonare Avatar answered Nov 08 '22 08:11

Shailesh Sonare