Posted By:
8 Mar, 2014 2:07 am PST

How to use break and continue statements in PHP?

 Use of break and continue statements to find prime numbers

break;

 break statement often used in loop to end the loop if certain condition is met. break statement causes loops to end. When break statement is encountered inside any loop control automatically passes to first statement after the loop;

 

Syntax:-

break; 

continue;

 
 

<?php

 

echo

"<h2 >";

echo "To

find whether number is prime or not <br ><br >";

 

$num = rand (1 ,100) ;

 

echo " ......... < br ><br >";

 

$flag = true ;

 

for( $i =2; $i < $num /2; $i ++)

{

 

if( $num % $i == 0)// condition

 

{

 

$flag = false ;

 

break ;// break statement

 

}

 

}

 

if( $flag )

 

{

 

echo "{ $num } is prime Number ";

 

}

 

else

 

{

 

echo "{ $num } is not prime Number ";

 

}

 

?>

 

BreakStatement.php

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<?php

 

echo "<h2 >";

 

echo " To print even number present in the array <br ><br >";

 

$numArray = array (1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,15 ,15 ,16 ,18 ,17 ,25 ,26 ,21 ,28);

 

echo " Actual Numbers Present in the array <br ><br >";

 

echo "<pre >";

 

print_r ( $numArray );

// print_r () prints human -readable information about a variable

 

echo "<br ><br > Even Number are ........ < br ><br >";

 

foreach ( $numArray as $tempValue )

 

{

 

if( $tempValue %2 != 0)// condition

 

continue ;// continue statement

 

else

 

echo " { $tempValue } ";

 

}

 

?>

Continue.php

 

 

continue statement is used to bypass one iteration inside loop when certain condition is met and continue with next iteration. It is often used with if statement.

BreakStatementOutput

 

ContinueStatementOutput

Attachment: BreakStatement.php


                                             How to use continue in PHP?

 

Continue is used within looping in order  to skip the rest part of the current loop iteration.It further continue execution at the condition  and then the beginning of the next iteration.

 

//To print numbers divisible by 5 from 1 to 25

 

<!DOCTYPE html>

<html>

<body>

<?php 

$x=1; 

echo 'list of number divisible by 5'; 

while ($x<=25) 

if (!($x / 10)==0) 

$x++; 

continue; 

else 

echo $x.'<br />'; 

$x++; 

}

?>

</body>

</html>

 

/*Output of the above program is:

list of number divisible by 5, 5

*/

Attachment: continue.php
Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud