ian
ian

Reputation: 49

Break, continue and exit issue while using with loop PHP 5.6

Switch statement works but, I am trying to break out of the loop but not having much luck.

I tried break, break 1, break 2 and continue but its not working. I am using PHP 5.6. Echo works fine and the data is coming out of the DB just fine. The problem is its printing three times.

    <?php 
    $sql = "SELECT * 
    FROM table1
    INNER JOIN verify
    WHERE uname='$showuser'";

    $result = mysqli_query($mysqli,$sql);

    if(mysqli_num_rows($result) > 0){  
        while($row = mysqli_fetch_array($result)){  
        $userid= $row["id"];
        $verify= $row["verified"];

    //NB! Notice how the If and While Loop are not closed here

    ?>

    <?php echo " stuff etc etc" ?>

        <?php 
            //I cant seem to some out of the IF statement. I tried BREAK, CONTINUE and EXIT.
            switch ($verify) {
            case '1': echo "<img src='passed.png' />"; break 1;
            case '3': echo "<img src='failed.png' />"; break 1;

            default:  echo "<img src='waiting.png' />"; break;
            }//END switch
        ?>


        <?php }} //END first IF & WHILE loops

        $sql2 = "SELECT * FROM table2 WHERE e.ctable_id = $userid ";

        $result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error($mysqli));

        if(mysqli_num_rows($result2) > 0){  
            while($row2 = mysqli_fetch_array($result2)){  

        ?>

        <?php echo " stuff etc etc" ?>

        <?php } } //END second IF & WHILE loops ?>

Everything was fine before I added the switch statement.

Upvotes: 1

Views: 1746

Answers (2)

Rickyras
Rickyras

Reputation: 71

To stop the rest of the script from running you can do

exit;

If you want to exit out of the if/else statement (if satisfied) do a

return;

Upvotes: 0

Scuzzy
Scuzzy

Reputation: 12322

break ends execution of the current for, foreach, while, do-while or switch structure.

break 1 will only break out of your "switch" statement, you will need break 2 to reach the while loop nesting level.

$count = 0;
while( $count++ < 10 )
{
  echo 'while';
  switch( true )
  {
    case true:
      echo 'switch';
      break 2; // TWO is needed here to break out of TWO levels of nesting
  }
}

https://www.php.net/manual/en/control-structures.break.php

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

Upvotes: 3

Related Questions