SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2012
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Noob question about difference in loops

    Hi All,
    I am taking an online intro PHP class and am having a hard time understanding why the following two statements don't output the same thing. The While loop outputs 0. 1. 2. 3. 4. FIVE 6. 7. 8. 9. 10. including the string "FIVE" as I expected, but the for loop does not. Instead it outputs 0 .1 .2 .3 .4 .5 .6 .7 .8 .9 .10 .11 Following are the two statements. Any help would be great because I am missing something super obvious.

    While Loop:
    <?php
    $count = 0;
    while ($count <= 10) {
    if ($count == 5) {
    echo "FIVE";
    echo "<br />";
    } else {
    echo $count . ". ";
    }
    $count++;
    }
    ?>

    FOR Loop:
    <?php
    for ($count=0; $count <= 10; $count++) {
    echo $count . " .";
    } if ($count == 5) {
    echo "FIVE";
    echo "<br />";
    } else {
    echo $count . ". ";
    }

    ?>

    Jim

  2. #2
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,069
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    Hi jskintauy ,

    The problem is quite simple actually, your for loop isn't formatted the same as your while loop. You have your IF statement outside of the loop for example.

    Below is the for loop that matches your while loop

    PHP Code:
    <?php
    for ($count=0$count <= 10$count++) {
        if (
    $count == 5) {
            echo 
    "FIVE";
            echo 
    "<br />";
        } else {
            echo 
    $count ". ";
        }


    ?>

  3. #3
    SitePoint Enthusiast
    Join Date
    May 2012
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow, that was easy now that I see the changes. Thanks so much. i could not see that the IF statement was outside the loop to save me even though I knew it wasn't being considered given that it provided ELSE even though the IF was true.
    Doh,

    Thanks so much

    Jim


Bookmarks

Posting Permissions

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