PHP Tutorial - PHP continue






continue causes PHP to skip the rest of the current loop iteration and go on to the next iteration.

Example

The following code uses the continue statement to start the next iteration.


<?php
        for ($i = 1; $i < 10; $i = $i + 1) {
                if ($i == 3) continue;
                if ($i == 7) break;
                print "Number $i\n";
        }
?>

The code above generates the following result.





Example 2

The following code shows how to continue a for loop.


<?php
    $usernames = array("grace","doris","gary","nate","missing","tom");
    for ($x=0; $x < count($usernames); $x++) {
        if ($usernames[$x] == "missing") 
           continue;
        echo "Staff member: $usernames[$x] <br />";
    }
?>

The code above generates the following result.





Example 3

The following code shows how to use continue statement to get ten random numbers,each greater than the next.


<?php//from w  w w.  j ava 2  s .  c o  m
  //init variables
  $count = 0;
  $max = 0;

  //get ten random numbers
  while($count < 10)
  {
    $value = rand(1,100);

    //try again if $value is too small
    if($value < $max)
    {
      continue;
    }

    $count++;
    $max = $value;
    print("$value <br>\n");
  }
?>

The code above generates the following result.