26 Sep 09 PHP Programming Tutorial: Continue



The Continue is used with PHP loops. Basically, it tells the loop to start over immediately. This is useful if you don’t want to execute code at a certain point during a loop.

For example, in our For Loops tutorial we used the following code:

<?php
    for ($x = 1; $x <= 5; $x++)
    {
        echo "Hello, I am loop iteration number $x.<br />"
    }
?>

But let’s say we didn’t want to echo out the third iteration. This is where we will use Continue.

<?php
    for ($x = 1; $x <= 5; $x++)
    {
        if ($x == 3)
        {
            continue; // tells PHP to start the loop over immediately
        }
        echo "Hello, I am loop iteration number $x.<br />"
    }
?>

So on the third iteration, the loop will immediately restart before using the echo statement. This code will output:

Hello, I am loop iteration number 1.
Hello, I am loop iteration number 2.
Hello, I am loop iteration number 4.
Hello, I am loop iteration number 5.

Notice the number 3 is missing, because we never gave it a chance to print to the screen.

Go back to Building PHP Scripts.

Leave a Comment