简体   繁体   中英

How can I break a loop which has a condition in it? (PHP)

I need to break a loop which has a condition inside it, on any circumstance which the condition meets the exception

like this:

for($l=0; $l<$subject_count; $l++){
    for($a=0; $a<$term_relatives_id_array_count; $a++){
        if($subject_array[$l]['id'] == $term_relatives_id_array[$a]['subject_id']){
            $subject_echo = true;
            break;
        }
        echo 'a';
    }
    if(!$subject_echo){
        echo '<li class="selectable_item" id="'.$subject_array[$l['id'].'">'.$subject_array[$l]['name_fa'];
        echo '</li>';
    }
}

I used echo 'a'; to see if break; works, but it doesn't break the inside loop what can I do?

Use break 1; to exit the current loop and break 2; out of 2.

Do you need to break both the inner and outer loops? In this case you should use break 2;

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

http://php.net/manual/en/control-structures.break.php

Example took from the above link:

<?php 
$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
?>

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

So in your case, check if you want to end the execution for both for loops, use break 2;

For more reference, refer break

And it may be that if condition is not met,so break may not be executed. So check the values also.

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