continue

(PHP 4, PHP 5, PHP 7)

continue используется внутри циклических структур для пропуска оставшейся части текущей итерации цикла и, при соблюдении условий, начала следующей итерации.

Замечание: Заметим, что в PHP структура switch считается циклической, и внутри нее может использоваться continue.

continue принимает необязательный числовой аргумент, который указывает на скольких уровнях вложенных циклов будет пропущена оставшаяся часть итерации. Значением по умолчанию является 1, при которой пропускается оставшаяся часть текущего цикла.

<?php
while (list($key$value) = each($arr)) {
    if (!(
$key 2)) { // пропуск нечетных чисел
        
continue;
    }
    
do_something_odd($value);
}

$i 0;
while (
$i++ < 5) {
    echo 
"Снаружи<br />\n";
    while (
1) {
        echo 
"В середине<br />\n";
        while (
1) {
            echo 
"Внутри<br />\n";
            continue 
3;
        }
        echo 
"Это никогда не будет выведено.<br />\n";
    }
    echo 
"Это тоже.<br />\n";
}
?>

Пропуск точки запятой после continue может привести к путанице. Пример как не надо делать.

<?php
for ($i 0$i 5; ++$i) {
    if (
$i == 2)
        continue
    print 
"$i\n";
}
?>

Ожидается, что результат будет такой:

0
1
3
4

Но, в PHP до версии 5.4.0, этот скрипт выведет следующее:

2

Потому что выражение continue print "$i\n"; воспринимается как единое выражение, и print вызывается только тогда, когда выражение $i == 2 истинно. (Возвращаемое значение от print передается к continue как числовой аргумент.)

Замечание:

Начиная с PHP 5.4.0, вышеприведенный пример вызовет ошибку E_COMPILE_ERROR.

Изменения, касающиеся оператора continue
Версия Описание
5.4.0 continue 0; больше не допускается. В предыдущих версиях это воспринималось точно также как и continue 1;.
5.4.0 Убрана возможность задавать переменную (например, $num = 2; continue $num;) в качестве числового аргумента.

Коментарии

In the same way that one can append a number to the end of a break statement to indicate the "loop" level upon which one wishes to 'break' , one can append a number to the end of a 'continue' statement to acheive the same goal. Here's a quick example:

<?
   
for ($i 0;$i<3;$i++) {
        echo 
"Start Of I loop\n";
        for (
$j=0;;$j++) {
           
            if (
$j >= 2) continue 2// This "continue" applies to the "$i" loop 
           
echo "I : $i J : $j"."\n";
        }
        echo 
"End\n";
    }
?>

The output here is:
Start Of I loop
I : 0 J : 0
I : 0 J : 1
Start Of I loop
I : 1 J : 0
I : 1 J : 1
Start Of I loop
I : 2 J : 0
I : 2 J : 1

For more information, see the php manual's entry for the 'break' statement.
2004-05-10 23:58:13
http://php5.kiev.ua/manual/ru/control-structures.continue.html
a possible explanation for the behavior of continue in included scripts mentioned by greg and dedlfix above may be the following line of the "return" documentation: "If the current script file was include()ed or require()ed, then control is passed back to the calling file." 
The example of greg produces an error since page2.php does not contain any loop-operations. 

So the only way to give the control back to the loop-operation  in page1.php would be a return.
2006-12-21 06:28:42
http://php5.kiev.ua/manual/ru/control-structures.continue.html
Автор:
For clarification, here are some examples of continue used in a while/do-while loop, showing that it has no effect on the conditional evaluation element.

<?php
// Outputs "1 ".
$i 0;
while (
$i == 0) {
   
$i++;
    echo 
"$i ";
    if (
$i == 1) continue;
}

// Outputs "1 2 ".
$i 0;
do {
   
$i++;
    echo 
"$i ";
    if (
$i == 2) continue;
} while (
$i == 1);
?>

Both code snippets would behave exactly the same without continue.
2007-12-27 19:01:07
http://php5.kiev.ua/manual/ru/control-structures.continue.html
Автор:
Using continue and break:

<?php
$stack 
= array('first''second''third''fourth''fifth');

foreach(
$stack AS $v){
    if(
$v == 'second')continue;
    if(
$v == 'fourth')break;
    echo 
$v.'<br>';
}
/*

first
third

*/

$stack2 = array('one'=>'first''two'=>'second''three'=>'third''four'=>'fourth''five'=>'fifth');
foreach(
$stack2 AS $k=>$v){
    if(
$v == 'second')continue;
    if(
$k == 'three')continue;
    if(
$v == 'fifth')break;
    echo 
$k.' ::: '.$v.'<br>';
}
/*

one ::: first
four ::: fourth

*/

?>
2009-04-16 08:58:36
http://php5.kiev.ua/manual/ru/control-structures.continue.html
The remark "in PHP the switch statement is considered a looping structure for the purposes of continue" near the top of this page threw me off, so I experimented a little using the following code to figure out what the exact semantics of continue inside a switch is:

<?php

   
for( $i 0$i 3; ++ $i )
    {
        echo 
' ['$i'] ';
        switch( 
$i )
        {
            case 
0: echo 'zero'; break;
            case 
1: echo 'one' XXXX;
            case 
2: echo 'two' ; break;
        }
        echo 
' <' $i'> ';
    }

?>

For XXXX I filled in

- continue 1
- continue 2
- break 1
- break 2

and observed the different results.  This made me come up with the following one-liner that describes the difference between break and continue:

continue resumes execution just before the closing curly bracket ( } ), and break resumes execution just after the closing curly bracket.

Corollary: since a switch is not (really) a looping structure, resuming execution just before a switch's closing curly bracket has the same effect as using a break statement.  In the case of (for, while, do-while) loops, resuming execution just prior their closing curly brackets means that a new iteration is started --which is of course very unlike the behavior of a break statement.

In the one-liner above I ignored the existence of parameters to break/continue, but the one-liner is also valid when parameters are supplied.
2010-03-24 08:36:53
http://php5.kiev.ua/manual/ru/control-structures.continue.html
Автор:
The most basic example that print "13", skipping over 2.

<?php
$arr 
= array(123);
foreach(
$arr as $number) {
  if(
$number == 2) {
    continue;
  }
  print 
$number;
}
?>
2011-02-26 23:22:18
http://php5.kiev.ua/manual/ru/control-structures.continue.html
Автор:
If you use a incrementing value in your loop, be sure to increment it before calling continue; or you might get an infinite loop.
2012-12-21 02:26:02
http://php5.kiev.ua/manual/ru/control-structures.continue.html

    Поддержать сайт на родительском проекте КГБ