0

When reading a PHP book I wanted to try my own (continue) example. I made the following code but it doesn't work although everything seems to be ok

$num2 = 1;

    while ($num2 < 19)
        {
            if ($num2 == 15) { 
            continue; 
            } else {
            echo "Continue at 15 (".$num2.").<br />";
            $num2++;
            }

        }

The output is

Continue at 15 (1).
Continue at 15 (2).
Continue at 15 (3).
Continue at 15 (4).
Continue at 15 (5).
Continue at 15 (6).
Continue at 15 (7).
Continue at 15 (8).
Continue at 15 (9).
Continue at 15 (10).
Continue at 15 (11).
Continue at 15 (12).
Continue at 15 (13).
Continue at 15 (14).

Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/php/continueandbreak.php on line 20

Line 20 is that line

if ($num2 == 15) { 

Would you please tell me what's wrong with my example ? I am sorry for such a Noob question

3 Answers 3

10

if you don't increment $num2 before the continue you will get into an infinite loop;

$num2 = 0;

while ($num2 < 18)
    {
            $num2++;
            if ($num2 == 15) { 
              continue; 
            } else {
              echo "Continue at 15 (".$num2.").<br />";
            }


    }
Sign up to request clarification or add additional context in comments.

1 Comment

Your code will still infinite loop; continue starts the next iteration of the loop without executing what comes after the if-else clause.
2

You don't even need continue there, your code equivalent to;

$num2 = 1;
while ($num2 < 19){
    if ($num2 != 15) { 
        echo "Continue at 15 (".$num2.").<br />";
        $num2++;
    }
}

If that's not what you're trying to achieve, you're using continue wrong.

2 Comments

This achieves the same result: an infinite loop that will eventually time out.
You definitely want to move $num2++; outside the if loop (below)
0

in php, use foreach for arrays and for for looping

for($num = 1; $num < 19; $num++) {
    if ($num != 15) { 
       echo "Continue at 15 (" . $num . ") . <br />";
       break;
    }   
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.