Skip to main content

The PHP Continue Statement

Where break ends a loop completely, continue only gives up on the current pass. PHP ignores the rest of the loop body for this iteration and goes on to the next one.

All four loop types support it:

  • for
  • while
  • do...while
  • foreach

PHP continue in For Loops

In a for loop, continue jumps past the remaining code in the body. The counter is still updated, and the loop goes on from there.

Continue in For Loop

Every number from 0 to 9 is printed except 4, because the echo is skipped when $x equals 4:

Prompt
Write a PHP script that uses a for loop from 0 to 9, skips the iteration when the counter equals 4 using continue, and prints the number on each other iteration.
Output: PHP script

PHP continue in While Loop

A while loop treats continue the same way: the rest of the body is skipped for this pass and PHP goes back to checking the condition.

Continue in While Loop

Nothing is printed for the pass where $x equals 4, and the loop then goes on. Notice that $x is increased before continue: the keyword jumps straight back to the condition, so without that line $x would stay at 4 and the loop would never end.

Prompt
Write a PHP script that uses a while loop from 0 to 9, skips the iteration when the counter equals 4 using continue, and prints the number on each other iteration. Increase the counter before continue, so the loop cannot get stuck.
Output: PHP script

PHP continue in Do While Loop

In a do...while loop, continue sends PHP straight to the condition at the bottom, skipping any code left in the body.

Continue in Do While Loop

When $i is 3, the echo is skipped, so the output jumps from 2 to 4:

Prompt
Write a PHP script that uses a do...while loop up to 6, skips the iteration when the counter equals 3 using continue, and prints the counter value on each other iteration.
Output: PHP script

PHP continue in Foreach Loop

Use continue in a foreach loop to leave out certain elements: PHP ignores the rest of the body for that element and picks up the following one.

Continue in Foreach Loop

All the colors are printed apart from "blue":

Prompt
Write a PHP script that uses a foreach loop over an array of colors, skips the iteration when the value is "blue" using continue, and prints each other color.
Output: PHP script