Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Beginner needs help with loop

    Hey. So I just started doing php and I encountered a little problem. When i run this
    PHP Code:
    <?php
    for ($i=3$i<=600$i+=3
    echo 
    $i.",";
    ?>
    It works, but some of the texts gets "hidden" because the text will just continue on without any column shift. But how do I implement a column shift, say every 10th number?
    Last edited by WeeDLY; 10-22-2012 at 05:22 PM.

  • #2
    Regular Coder Redcoder's Avatar
    Join Date
    May 2012
    Location
    /dev/null
    Posts
    334
    Thanks
    2
    Thanked 48 Times in 47 Posts
    I'm guessing that by column shift you mean new line.

    You can add a small if statement that tests whether a number is divisible by 10.

    So it becomes:

    PHP Code:
    <?php
    for ($i=3$i<=600$i+=3) {
    if(
    $i%10 == 0){
    echo 
    $i."<br />";
    }
    else{
    echo 
    $i.",";
    }
    }
    ?>
    Last edited by Redcoder; 10-22-2012 at 04:10 PM.

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    What is a "column shift"?
    The loop itself is fine, although with any control branch I'd recommend using { and } regardless of how many lines it has. It looks silly combining multiples:
    Code:
    if (false)
        print 'never gets here';
    else
    {
        print 'Got here.';
        define('GOTSHERE', 'here I am');
    }

  • #4
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for the help
    And yes, column shift was new line :P

  • #5
    Regular Coder
    Join Date
    Sep 2007
    Location
    Grahamstown, South Africa
    Posts
    237
    Thanks
    6
    Thanked 17 Times in 17 Posts
    Bored at work...

    PHP Code:

    $b 
    = !((bool)$i 10) ?  "<br>" ",";
    echo (
    $i $b); 
    I challenge you all to come up with a more convoluted way of doing this.

  • #6
    Regular Coder
    Join Date
    Sep 2007
    Location
    Grahamstown, South Africa
    Posts
    237
    Thanks
    6
    Thanked 17 Times in 17 Posts
    Heres another more retarded version, utilizing some amazing typecasting functions from php:

    PHP Code:

    $tmp 
    = (string)$i;
    $b = !($tmp{strlen($tmp) -1}) ? "<br>" ",";
    echo(
    $i $b); 
    Last edited by idalatob; 10-23-2012 at 09:43 AM. Reason: compacted it a bit


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •