PHP break

PHP break is a keyword use with mostly for, do-while, while and switch structure.
PHP break ends execution of current loop.
break keyword can accept numeric arguments. By default value is 1. It will enclose only one immediate structure.
For example:
break 1 or break – It ends execution of one loop.
break 2 – It ends execution of 2 loops.

 

Note: From PHP5.4.0, break 0; is no longer valid.
In previous versions it was interpreted the same as break 1;
 

Example

Output:

In above example you can see only one value of a is print because of break.
break ends the current loop.
Due to break only one time condition is checked and one time loop is executed.
If there will not any break then loop will execute 10 times.

 

PHP break with switch structure:

We see the use of break in switch structure chapter.

Output

 

break with arguments

Output

Now understand how break work in switch structure.
There are 2 loops, outer loop while and inner loop switch.
At beginning, at $a = 0; both while and switch condition is true.
Therefore it print statements of case having matching case value i.e. Number 0.
But after matching case 0, there is no break so it print next statements upto break.
AS you can see in output when $a = 0, it print Number 0, Number 1, Number 2.
break 1 results termination of switch and increment $a by 1.
In this way, when $a = 1 and $a = 2, it will print respected matching case statements.
When $a = 3, only “Number 3” is print and it break the execution of both switch and while loop due to break argument 2.

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.