Home » Php » loops – php Algorithm to print a aa aaa ab aab till zzz

loops – php Algorithm to print a aa aaa ab aab till zzz

Posted by: admin July 12, 2020 Leave a comment

Questions:

Hi i need To print from a to zzz upto 3 letters , for example my output should be

A
B
.
.
.
Z
AA
AB
.
.
AZ
BA
BB
.
.
.
ZZ
AAA
AAB
.
.
.
.
ZZZ

I was trying hard for past 5 hours , I cant find any logic and i tried below code

<?php
for ($i=65; $i<=90; $i++) { 
for ($i=65; $i<=90; $i++) {     
for ($i=65; $i<=90; $i++) {     
    echo chr($i).chr($i).chr($i)."<br>";      
}
}
}
?>
How to&Answers:

PHP has a convenient feature where incrementing a string works exactly as you describe.

So all you need is:

for( $i="A"; $i!="ZZZ"; $i++) {
    echo $i."<br />";
}

EDIT: revised solution that prints ‘ZZZ’ (instead of ‘ZZY’) last:

$i = 'A';
do {
  echo $i . '<br />';
} while ( $i++ != 'ZZZ' );

Answer:

I’m not sure if you have it working perfectly yet but your code needed a very minor tweak:

http://phpfiddle.org/lite/code/zqh-dyv