简体   繁体   中英

Break While and Foreach Loop

I have the following code below, my question is, I want to break out of the while loop if the user enters "n" and also continue with the next foreach interation. Please see my comment within.

foreach($nodeid as $nid){

    $query= $dbh->query("SELECT * FROM Nodes WHERE Node_ID = '$nid' AND New = 1")or die(mysql_error());

    if($query->rowCount() > 0)
    { 
        while (1) {
            fputs(STDOUT, "\n"."***New Node*** : $nid \n Do you want to add ? [y,n]: ");
            $response = strtolower(trim(fgets(STDIN)));
            if( $response == 'y' ) {
                #do something then break and go to next foreach.
            } elseif( $response == 'n' ) {
                #go to next foreach $nid
            } else {
                echo "\n", "I don't understand your option, let's try this again", "\n";
                continue;
            }
        }
    }
}

You can:

continue 2;

in this case. This will continue with the next run of the outer foreach loop.

However, as @Tularis told in comments, a simple break would have the same effect here because no code is following the while loop. (and might be easier to read)


About the query. It looks like it would be better here to issue only one database query for all ids, using the IN statement:

$ids = impldode(',', $nodeids); // assuming the ids are integers
$query= $dbh->query("SELECT * FROM Nodes WHERE Node_ID IN $ids AND New = 1")

You should use break notation:

    $foreach = array('a','b','c','d');
    $while = array('a','b','c','d');
    foreach($foreach as $key => $value){
        echo 'in foreach = '. $value.'<br/>';
        reset($while);
        while(current($while)){
            echo '&nbsp;&nbsp; in while = '. current($while).'<br/>';
            if(current($while) == 'b'){
                break;
            }
            next($while);
        }
    }

result :

in foreach = a
   in while = a
   in while = b
in foreach = b
   in while = a
   in while = b
in foreach = c
   in while = a
   in while = b
in foreach = d
   in while = a
   in while = b

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