29 Sep 09 PHP Programming Tutorial: Break



The Break statement is often used with PHP Loops or Switch. Break tells PHP to stop what it is doing. For example, if you were to echo out an unknown amount of table rows, but you wanted to stop at 20 no matter how many existed, then you could tell PHP to “break” at 20.

Here’s a basic example of the break in use:

<?php
    for ($x = 1; $x <= 5; $x++)
    {
        if ($x == 3)
        {
            break; // tells PHP to stop the loop.
        }
        echo "Hello, I am loop iteration number $x.<br />"
    }
?>

So on the third iteration, the loop will stop executing the code and end the loop. This code will output:

Hello, I am loop iteration number 1.
Hello, I am loop iteration number 2.

Without the If and Break statements, the loop would have continued until it hit 5.

Go back to Building PHP Scripts.

Leave a Comment