CodesJava

Easy learning with example program codes

PHP Break


PHP break statement is used to break the execution of current loop in between the loop or to prevent the code to check the next switch case.

Break statement breaks the continuity of the containing loop only, i.e, external loops will not get affected because of Break statement in inner loop.

Syntax:

loop/conditions statements
{
statements;  
break; 
}

Example 1: Use of Break Statement in Switch Case

<!DOCTYPE html>
<html>
<body>
 
<?php
$car = "Hyundai";
 
switch ($car) {
    case "Honda":
        echo "Your favorite car is Honda!";
        break;
    case "BMW":
        echo "Your favorite car is BMW!";
        break;
    case "Hyundai":
        echo "Your favorite car is Hyundai!";
        break;
    default:
        echo "Your favorite car is neither Honda, BMW, nor Hyundai!";
}
?>
 
</body>
</html>

Output

Your favorite car is Hyundai!

Example 2: Use of Break Statement in For Loop

<!DOCTYPE html>
<html>
<body>
 
<?php  
for ($i = 0; $i <= 10; $i++) {
echo "The number is: $i <br>";
	if ($i =="5") 
	{
		break;
	}	
}
?>  
 
</body>
</html>

Output

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

Example 3: Use of Break Statement in Nested For loop

<!DOCTYPE html>
<html>
<body>
 
<?php  
for ($i = 0; $i <= 2; $i++)
{
 	for ($j = 0; $j <= 5; $j++)
{
$sum = $i+ $j;
echo "$sum<br>";
if ($j =="3")
    	{
        	break;
    	}
}
echo "<br>";
}
?>  
</body>
</html>

Output

0
1
2
3
 
1
2
3
4
 
2
3
4
5
Posted in PHP   


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap