Php break one loop

Php break one loop

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

Замечание: В PHP оператор switch считается циклическим и внутри него может использоваться continue . Если continue не передано аргументов, то он ведёт себя аналогично break , но выдаёт предупреждение о возможной ошибке. Если switch расположен внутри цикла, continue 2 продолжит выполнение внешнего цикла со следующей итерации.

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

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

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

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

Изменения, касающиеся оператора continue

Версия Описание
7.3.0 continue внутри switch , использующееся как замена break для switch будет вызывать ошибку уровня E_WARNING .
Читайте также:  Правый нижний угол html

User Contributed Notes 20 notes

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:

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 ‘ ‘ ;
>

— 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.

Источник

PHP Break and Continue

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to «jump out» of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

Example

PHP Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example

Break and Continue in While Loop

You can also use break and continue in while loops:

Break Example

Continue Example

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

PHP break

Summary: in this tutorial, you will learn how to use the PHP break statement to end the execution of the current for , do. while , while And switch statements.

Introduction to the PHP break statement.

The break statement terminates the execution of the current for , do. while , while , or switch statement. This tutorial focuses on how to use the break statement with the loops.

Typically, you use the break statement with the if statement that specifies the condition for the terminating loop.

The break statement accepts an optional number that specifies the number of nested enclosing structures to be broken out of.

If you don’t specify the optional number, it defaults to 1 . In this case, the break statement only terminates the immediate enclosing structure.

Using PHP break statement in a for loop

The following example illustrates how to use the break statement in a for loop:

 for ($i = 0; $i < 10; $i++) < if ($i === 5) < break; > echo "$i\n"; >Code language: HTML, XML (xml)

The for statement would execute 10 times from 0 to 9. However, when the $i variable reaches 5 , the break statement ends the loop immediately. The control is passed to the statement after the for statement.

Using PHP break statement in a do…while loop

The following example illustrates how to use the break statement inside a do. while loop:

 $j = 0; do < if ($j === 5) < break; > echo "$j\n"; $j++; > while ($j 10);Code language: HTML, XML (xml)

In this example, the do-while loop executes only five iterations. The variable $j is increased by one in each iteration. When the $j variable reaches 5 , the break statement terminates the loop immediately.

Using PHP break statement in a while loop

The following example shows how to use the break statement in a while loop:

$k = 0; while ($k 10) < if ($k === 5) < break; > echo "$k\n"; $k++; >Code language: PHP (php)

This example also displays five numbers from 0 to 4 . In each iteration, the variable $k is increased by one. The break statement terminates the loop immediately when the $k variable reaches 5 .

Using break statement to jump out of a nested loop

The following example illustrates how to use the break statement to break of out a nested loop:

$i = 0; $j = 0; for ($i = 0; $i < 5; $i++) < for ($j = 0; $j < 3; $j++) < if ($i === 3) < break 2; > echo "($i, $j)\n"; > >Code language: PHP (php)
(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2)

In this example, when the variable $i reaches 3 , the break statement terminates the inner and outer loops immediately.

By default, the break statement only ends the enclosing loop. But in this example, we use the number 2 in the break statement; therefore, it terminates both inner and outer loops.

If you remove the number 2, you will see a different output:

 $i = 0; $j = 0; for ($i = 0; $i < 5; $i++) < for ($j = 0; $j < 3; $j++) < if ($i === 3) < break; > echo "($i, $j)\n"; > >Code language: HTML, XML (xml)
(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) (4, 0) (4, 1) (4, 2)

In this example, the break statement ends the inner loop when $i is 3 .

Summary

  • Use the break statement to immediately terminate the execution of the current for , do. while , and while loops.

Источник

Операторы break и continue в PHP

Очень часто при работе с циклами требуется пропустить одну итерацию и перейти к следующей. Не менее часто возникает необходимость и вовсе нужно прервать цикл ещё до того, как он должен был завершиться. Для этого используются специальные операторы PHP – continue (переход к следующей итерации) и break (остановка цикла).

Оператор break завершает цикл полностью, continue просто сокращает текущую итерацию и переходит к следующей итерации:

while ($foo) < continue; --- возвращаемся сюда --┘ break; ----- покидаем цикл ----┐ > | 

Прерывание цикла - break

Для примера напишем простейший цикл, внутри которого мы будем выяснять, есть ли искомое число в массиве, или нет:

Пример

 $array = [5, 9, 6, 7, 33, 2, 48, 7, 18, 17];

$number = 7;
$isNumberFound = false;
foreach ($array as $value) echo 'Сравниваем с числом значение ' . $value . '
';
if ($item === $number) $isNumberFound = true;
>
>

echo $isNumberFound ? 'Число найдено' : 'Число не найдено';
?>

Результат выполнения кода:

Сравниваем с числом значение 5 Сравниваем с числом значение 9 Сравниваем с числом значение 6 Сравниваем с числом значение 7 Сравниваем с числом значение 33 Сравниваем с числом значение 2 Сравниваем с числом значение 48 Сравниваем с числом значение 7 Сравниваем с числом значение 18 Сравниваем с числом значение 17 Число не найдено

Перед циклом мы инициализировали переменную $isNumberFound , назначение которой — хранить информацию о том, найдена ли искомая цифра в массиве или нет. Изначально приравниваем её к false .

В цикле идём по массиву и сравниваем каждый его элемент $value с числом. Когда совпадение найдено значение переменной $isNumberFound станет равной true и мы уже знаем, что искомая цифра в массиве есть.

Из примера видно, что все элементы массива сравнивались с искомой цифрой. А что если мы хотим найти цифру 7 и на этом завершить работу цикла? Для этого используем оператор break :

Пример

 $array = [5, 9, 6, 7, 33, 2, 48, 7, 18, 17];

$number = 7;
$isNumberFound = false;
foreach ($array as $value) echo 'Сравниваем с числом значение ' . $value . '
';
if ($item === $number) $isNumberFound = true;
break;
>
>

echo $isNumberFound ? 'Число найдено' : 'Число не найдено';
?>

Результат выполнения кода:

Сравниваем с числом значение 5 Сравниваем с числом значение 9 Сравниваем с числом значение 6 Сравниваем с числом значение 7 Число найдено

В примере мы останавливаем работу цикла, как только искомая цифра 7 найдена. При этом сценарий завершился с гораздо меньшим числом итераций.

Прерывание итерации - continue

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

В следующем примере пропускается значение 3 цикла for:

Пример

 for ($x = 0; $x < 10; $x++) if ($x == 3) continue; 
>
echo "Число: $x
";
>
?>

Результат выполнения кода:

Операторы break и continue применяются в циклах for, foreach, while, do-while или switch

Источник

Оцените статью