问题
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?
回答1:
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.
回答2:
Use break 1;
to exit the current loop and break 2;
out of 2.
回答3:
Do you need to break both the inner and outer loops? In this case you should use break 2;
回答4:
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;
}
}
?>
来源:https://stackoverflow.com/questions/17475470/how-can-i-break-a-loop-which-has-a-condition-in-it-php