DJ Mike's Tutorials: PHP

Break(), Continue(), & Die()

< ^ >

Break

The break statement provides a way to break out of a loop and will usually be used with a conditional statement. The following code will divide 10 by $counter. When $counter is equal to zero, you get a math error.



<?
for ( $counter=-5$counter<=5$counter++ )

$var 10/$counter;
echo 
"$var<br />"; }
?>


Output of code above:

-2
-2.5
-3.33333333333
-5
-10

Warning: Division by zero in /home/djmike/public_html/mike/tutorials/php/break.php on line 42

10
5
3.33333333333
2.5
2

To avoid dividing by zero you can use an if statement to see if $counter is equal to zero and if it is, use a break statement to break out of the loop.



<?
for ( $counter=-5$counter<=; $counter++ )
{
if ( 
$counter == 0)
{ break; }
$var 10/$counter;
echo 
"$var<br />";
}
?>


Output of code above:

-2
-2.5
-3.33333333333
-5
-10

Continue

Instead of breaking out of the loop, continue will end the current itineration of the loop and start the next one. For the example above, you avoid the divide by zero error but you get all the way to the end of the loop



<?
for ( $counter=-5$counter<=5$counter++ )
 {
  if ( 
$counter == 0)
    { continue; }
     
$var 10/$counter;
      echo 
"$var<br />"
 }
?>


Output of code above:

-2
-2.5
-3.33333333333
-5
-10
10
5
3.33333333333
2.5
2

die()

If the die() function is executed, the entire script ends and it has a message, the message is displayed. It can be used to indicate an incorrect password:



if ( $pass != "password" )
    { die("The password you entered is invalid"); }


or use it with a function with or to kill the script if some essential function fails:



mysql_connect("host", "user", "password")
or die("Database not available. Try later.");
< ^ >


Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>