Thursday, 25 December 2014

Use of Continue and Break Keywords in PHP



Well these both keywords continue and break  are very familiar keywords in every programming language and are used vastly in daily programming exercises.  I will explain where these keywords can be used in programming like loops (for loop, while loop, do while loop), and switch case etc.  well both break and continue have very different roles in a program  and there functioning is quite different, I will explain their differences with proper practical examples.

Break keyword and its functioning

In every programming language every keyword have their logical meaning, so as per the logical meaning of break, it means that to break something midway and came out of that thing. Mostly it is used in loops and switch case.  Below is the example with proper explanation and output result of break keyword.

Example 1:-
<?php
For($i=1; $i<=10; $i++)
{
echo  $i;
}
?>
Output result example 1 :--   1 2 3 4 5 6 7 8 9 10
Example 2:-
<?php
For($i=1; $i<=10; $i++)
{
echo  $i;
If($i==5) break;
}
?>
Output result  example 2  :-   1 2 3 4 5
See in example 2  we have used the break keyword in for loop which is printing from no. 1 to 10, and we have used the break keyword on condition when value of variable I will be 5 the loop will break and the control  shifts out of loop. So in example 2 it is printing only upto number 5.

Continue keyword and its functioning

The keyword continue is also used in the loops, but unlike break keyword it is used for continuing the loop. In simple words the point where continue keyword will be used in the loop the loop will not function below that point and continue from there only.  This thing will be more clear by the following example.
Example 3:-                                                                                       
<?php
For($i=1; $i<=5; $i++)
{
echo “hello”;
echo “world,”;
}
?>
Output result example 3 :-  hello world, hello world, hello world, hello world, hello world
Example 4 :-
<?php
For($i=1; $i<=10; $i++)
{
echo “hello”;
If($i>=3) continue;
echo “world,”;
}        
?>
Output result example 4  :-   hello world, hello world,  hello,  hello,  hello

See in example 4 in result it has printed complete hello world only two times and the rest of time it printed only hello.  Because when two times it printed complete sentence hello world, on third time when the if condition becomes true($i>=3), then continue keyword executed and it continued the loop from that point to increment the value of $i=4 and didn’t printed the below statement world.  So in simple words the point where continue keyword will execute the statements below continue keyword in a loop will not be printed.

No comments:

Post a Comment