简体   繁体   中英

Break while loop inside for loop

How can I break while loop and for loop too when while loop is true?

<?php
for($i=0; $i<4; $i++){
    $result = mysql_query("SELECT * FROM table WHERE weight='$i'");
    while($row = mysql_fetch_array($result)){
        echo $row['cell'];
        break; //I need to break the while loop and the for loop too in this line exactly, when he find and echo the "cell"!
    }
}
?>

It is

break 2;

References:

...

Use Flags:

One flag inside while : Set this flag to 1 when you break while

One flag in outer for loop: If while loop flag is set then break for loop

Instead of doing a break why not do the following

SELECT * FROM table WHERE weight BETWEEN 0 AND 3

OR just

SELECT * FROM table WHERE weight = 0

You would be limiting querying the database multiple times and probably takes less time but you'd wouldn't notice it with a query like this.

Not sure why you there is a for loop then break on first iteration when you can just query the database and echo something. Unless OP has other plans for this code and reduced the code for SO the loop is really unnecessary.

use exit instead of break .

break results exit from current iteration while exit results exit from overall pgm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM