Home >Backend Development >PHP Problem >An in-depth analysis of three ways to break out of loops in PHP
This article will give you an in-depth understanding of the three methods of jumping out of the loop in PHP (contiue, break and exit). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Three ways to break out of the loop in php
1.break statement
1. Used for switch statements, for, while, do...while, foreach, used to interrupt statements.
2. The number followed by break indicates how many levels of loops to jump out of. By default, no number is added to indicate one level of loops to jump out of.
3. A loop can contain multiple break statements, but only the statement executed for the first time is valid.
<?php for ($i=0; $i <5 ; $i++) { for ($j=0; $j <5 ; $j++) { echo $j; echo '<br />'; break; } echo $i; } ?>
The running result is:
But if we add 2 after break, the output result will be 0.
2. The continue statement
can only be used in loop statements. Breaking out of this loop does not end the entire loop.
<?php for ($i=0; $i <5 ; $i++) { for ($j=0; $j <5 ; $j++) { echo $j; continue; } echo $i; echo '<br />'; } ?>
The result of its operation is:
##Three.exit() statement/die statement
Ends the execution of the entire program, which is a function.Syntax:exit(parameter)
<?php for ($i=0; $i <5 ; $i++) { for ($j=0; $j <5 ; $j++) { echo $j; exit(); } echo $i; echo '<br />'; } ?>It ends the entire program directly, so the result after we run it is only 0. Recommended learning: "
PHP Video Tutorial"
The above is the detailed content of An in-depth analysis of three ways to break out of loops in PHP. For more information, please follow other related articles on the PHP Chinese website!