user887515
user887515

Reputation: 804

PHP - loop through letters

I am trying to loop through letters rather than numbers.

I am trying to do this using chr and the number equivalent but it doesn't seem to be happening!

I want four letter loop.

So AAAA, AAAB, AAAC etc through to ZZZZ - and yes I know this will likely take a while to execute!

Upvotes: 21

Views: 21534

Answers (3)

Moak
Moak

Reputation: 12885

Another way to solve this

$i = 'AAAA';
do {
  echo $i . "\n";
  $i++;
} while( $i !== 'AAAAA');

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

for( $x = "AAAA"; ; $x++) {
    echo $x."\n";
    if( $x == "ZZZZ") break;
}

Incrementing a letter will cycle it through the alphabet similar to the column names in Excel.

Upvotes: 27

lll
lll

Reputation: 12889

Why don't you make an array of letters and then use nested loops:

$letters = range('A', 'Z');

foreach ($letters as $one) {
  foreach ($letters as $two) {
    foreach ($letters as $three) {
      foreach ($letters as $four) {
        echo "$one$two$three$four";
      }
    }
  }
}

Upvotes: 30

Related Questions