1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Printing A to Z using for statement

Discussion in 'PHP' started by krishmk, Oct 9, 2008.

  1. #1
    I was just playing around the for statement in php to output the letters "A" to "Z".

    <?php
    for ($letters=A; $letters <= Z; $letters++)
    {
    print ("$letters, ");
    }
    ?>

    The above code works fine if "$letters <= Y" or any other letter before "Z". But if I use "Z" it goes beyond Z and includes double letters like "AA, AB, AC till YZ.

    Anyone know how to make it stop at "Z".
     
    krishmk, Oct 9, 2008 IP
  2. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #2
    I take another route

    for ($i=1;$i<=26;$i++) {
    if (!isset($letters)) { $letters=A; }
    print ("$letters, ");
    $letters++;
    }
    PHP:
     
    ads2help, Oct 9, 2008 IP
  3. krishmk

    krishmk Well-Known Member

    Messages:
    1,376
    Likes Received:
    40
    Best Answers:
    0
    Trophy Points:
    185
    #3
    Thanks!
    W'd appreciate if you could let me know how it works in reverse order "Z to A"
    I tried
    <?php
    for ($i=26;$i>=1;$i--) {
    if (!isset($letters)) { $letters=Z; }
    print ("$letters, ");
    $letters--;
    }
    ?>
    
    PHP:
    It just prints "Z" 26 times. But the above code works fine with numbers "26 to 1".
     
    krishmk, Oct 9, 2008 IP
  4. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #4
    you dont have to change the loop to this for ($i=26;$i>=1;$i--) {
    because we just need the for loop to print 26 alphabet thats all.
    but its no hurt.

    decrement? cant seems to find a better way...Maybe you can try this:

    
    for ($i=1;$i<=26;$i++) {
    if (!isset($letters)) { $letters=A; }
    $string .= ",$letters ";
    $letters++;
    }
    $string = strrev($string);
    
    // to test it
    print $string;
    
    PHP:
     
    ads2help, Oct 9, 2008 IP