Continue
As a PHP developer, you may have used loops to iterate through arrays or perform other tasks. The «continue» keyword is a control structure in PHP that allows you to skip over certain iterations of a loop based on a condition. In this article, we will explore the syntax and usage of the «continue» keyword in depth, and provide plenty of examples to help you master this important PHP feature.
Syntax
The «continue» keyword is used to skip over certain iterations of a loop in PHP. Here is the basic syntax for using the «continue» keyword in PHP:
In this example, the «continue» keyword is used to skip over the current iteration of the loop and move on to the next iteration.
Examples
Let’s look at some practical examples of how the «continue» keyword can be used:
In these examples, we use the «continue» keyword to skip over certain iterations of a loop based on a condition.
Benefits
Using the «continue» keyword has several benefits, including:
- Improved code efficiency: The «continue» keyword can help you skip over unnecessary iterations of a loop, making your code run more efficiently.
- Simplified code: The «continue» keyword can help you simplify your code by allowing you to skip over certain iterations of a loop based on a condition, rather than using complex if-else statements.
Conclusion
In conclusion, the «continue» keyword is a powerful tool for PHP developers, allowing them to skip over certain iterations of a loop based on a condition and improve the efficiency and readability of their code. We hope this comprehensive guide has been helpful, and we wish you the best of luck as you continue to develop your PHP skills.
PHP: break, continue и goto
Часто бывает удобно при возникновении некоторых условий иметь возможность досрочно завершить цикл. Такую возможность предоставляет оператор break . Он работает с такими конструкциями как: while, do while, for, foreach или switch .
Оператор break может принимать необязательный числовой аргумент, который сообщает ему, выполнение какого количества вложенных структур необходимо завершить. Значением числового аргумента по умолчанию является 1, при котором завершается выполнение текущего цикла. Если в цикле используется оператор switch , то break/break 1 выходит только из конструкции switch .
Разумеется, иногда вы предпочли бы просто пропустить одну из итераций цикла, а не завершать полностью работу цикла, в таком случае это делается с помощью оператора continue .
continue
Для остановки обработки текущего блока кода в теле цикла и перехода к следующей итерации можно использовать оператор continue . От оператора break он отличается тем, что не прекращает работу цикла, а просто выполняет переход к следующей итерации.
Оператор continue также как и break может принимать необязательный числовой аргумент, который указывает на скольких уровнях вложенных циклов будет пропущена оставшаяся часть итерации. Значением числового аргумента по умолчанию является 1, при которой пропускается только оставшаяся часть текущего цикла.
Обратите внимание: в процессе работы цикла было пропущено нулевое значение переменной $counter , но цикл продолжил работу со следующего значения.
goto является оператором безусловного перехода. Он используется для перехода в другой участок кода программы. Место, куда необходимо перейти в программе указывается с помощью метки (простого идентификатора), за которой ставится двоеточие. Для перехода, после оператора goto ставится желаемая метка.
Простой пример использования оператора goto :
Оператор goto имеет некоторые ограничение на использование. Целевая метка должна находиться в том же файле и в том же контексте, это означает, что вы не можете переходить за границы функции или метода, а так же не можете перейти внутрь одной из них. Также нельзя перейти внутрь любого цикла или оператора switch . Но его можно использовать для выхода из этих конструкций (из циклов и оператора switch ). Обычно оператор goto используется вместо многоуровневых break .
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
COLOR PICKER

Get certified
by completing
a course today!

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.
Difference between break and continue in PHP?
What is the difference between break and continue in PHP?
10 Answers 10
break ends a loop completely, continue just shortcuts the current iteration and moves on to the next iteration.
This would be used like so:
break exits the loop you are in, continue starts with the next cycle of the loop immediatly.
break ends execution of the current for, foreach, while, do-while or switch structure.
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
So depending on your need, you can reset the position currently being executed in your code to a different level of the current nesting.
Also, see here for an artical detailing Break vs Continue with a number of examples