Page 1 of 1

Please explain

Posted: Sun Nov 21, 2010 9:32 pm
by cybershot
I am learning php. I am working with a loop

Code: Select all

for($count = 0; $count <= 10; $count++)
	{
		if($count == 5)
		continue;
	}
	echo $count . ", ";
this is suppose to print 0 - 4 and 6 - 10 skipping five. but what it does is echo 11. I don't understand why

Re: Please explain

Posted: Sun Nov 21, 2010 9:36 pm
by Celauran
Are you sure you didn't type $count < 10 by mistake? The code as it is written in your post does precisely what you describe.

Re: Please explain

Posted: Sun Nov 21, 2010 9:37 pm
by cybershot
you lost me

Re: Please explain

Posted: Sun Nov 21, 2010 10:09 pm
by McInfo
Here is your code with slightly different formatting.

Code: Select all

for($count = 0; $count <= 10; $count++) {
    if ($count == 5) {
        continue;
    }
}
echo $count . ", ";
The loop essentially accomplishes nothing except to increment $count to 11. After the loop is done, the echo statement executes one time.

Re: Please explain

Posted: Sun Nov 21, 2010 10:16 pm
by cybershot
right, but I copied it from a video tutorial and the tutorial clearly shows that code echoing 0 - 4 6 - 10. so i do not understand why it doesn't seem to execute the if statement

Re: Please explain

Posted: Sun Nov 21, 2010 10:21 pm
by McInfo
The explicit continue statement has no noticeable effect because it appears at the bottom of the loop and continue is already always implied by the bottom of the loop. In other words, there is nothing to skip by explicitly jumping to the next iteration of the loop. Continuing in a for loop does not skip the iteration expression ($count++). The echo statement is not inside the loop.

Re: Please explain

Posted: Mon Nov 22, 2010 6:07 am
by Celauran
I can't believe I missed it earlier. It's the positioning of the braces which is what's causing yours to print only 11.

Your code:

Code: Select all

for($count = 0; $count <= 10; $count++)
       {
          if($count == 5)
          continue;
       }
       echo $count . ", ";
The code that behaves as you described:

Code: Select all

for($count = 0; $count <= 10; $count++)
{
    if($count == 5)
        continue;
    echo $count . ", ";
}
For clarity, use braces around the conditional as well:

Code: Select all

for($count = 0; $count <= 10; $count++)
{
    if($count == 5)
    {
        continue;
    }
    echo $count . ", ";
}

Re: Please explain

Posted: Mon Nov 22, 2010 1:43 pm
by cybershot
man. I don't know how I missed it either Celauran. That is what I was looking for. Thanks everyone.