PHP Break and Continue

break

break will end the execution inside the block of following statements:

for, foreach, while, do-while and switch structure

Syntax:

numeric number default value is 1, which tells to PHP processor that how many nested enclosing structures are to be skipped.
Syntax Example:

Where both break and break 1 are equivalent.

Example explanation:
break end the execution in the current block
{
break;
}
-> end this block
break 2 end the execution in the 1st outer of current block
{
{break 2;}
}
-> end this block
break 3 end the execution in the 2nd outer of current block
{
{
{break 3;}
}
}
-> end this block

Consider the following example which contain while loop and switch structure.

Example:

Run the above example

  • We just iterate the while loop, the while($i++) is a endless process and it always return true.
  • To terminate the loop process, we have used break and break 2.
  • Inside case 2, we have used break, which will end the execution in the current block, ie) switch block.
  • Inside case 4, we have used break 2, which will end the execution in the outer block, ie) while loop block and so the process ended at this point.
More Examples:

Example for break with foreach loop

Example for break with for loop

continue

continue will stop the execution at the point and continue the remaining looping process inside the block of following statements:

for, foreach, while, do-while and switch structure

Syntax:

numeric number default value is 1, which tells to PHP processor that how many levels of enclosing loops it should skip to continue for remaining iteration.

Consider the following example which contain while loop, for loop and if statement.

Example:

Run the above example

  • We have used continue 1; inside if($i == 2) this will stop the execution at this place/point and continue for loop iteration. So echo "inside for loop. i = $i and j = $j <br />"; is not executed.
  • We have used continue 2; inside else if($i == 4) this will stop the execution at this place/point and continue while loop iteration. So both echo "inside for loop. i = $i and j = $j <br />"; and echo"i = $i, inside while loop <br />"; is not executed inside while of $i = 4 block and continue while of $i = 5 block.
Please follow and like us:
error

Leave a Reply

Your email address will not be published. Required fields are marked *