2016-08-03 4 views
1

複数のwhileループで要素を探していますが、要素が見つかった場合は、次のwhileループを確認する必要はありません。このようなことをどうすれば実現できますか?中断して次のループをスキップ

while(something) { 
    if (this = key) { 
     // break this loop and skip the next ones. Otherwise proceed to next. 
    } 
} 

while(somethingelse) { 
    if (this = key) { 
     // break this loop and skip the next ones. Otherwise proceed to next. 
    } 
} 

while(somethingthird) { 
    if (this = key) { 
     // break this loop and skip the next ones. Otherwise stop looking. 
    } 
} 
+0

恐ろしい... goto'を使うことができます!私は今シャワーを浴びている。 –

答えて

3

あなたの条件は次のように、以前しばらくチェックした場合は知っている変数(boolean)を使用します。

$breakAll = false; //default false 
while(something) { 
    if (this = key) { 
     // break this loop and skip the next ones. Otherwise proceed to next. 
     $breakAll = true; //now break all whiles 
    } 
} 

while(somethingelse && !breakAll) { 
    if (this = key) { 
     // break this loop and skip the next ones. Otherwise proceed to next. 
     $breakAll = true; //same here 
    } 
} 

while(somethingthird && !breakAll) { 
    if (this = key) { 
     // break this loop and skip the next ones. Otherwise stop looking. 
    } 
} 
2

リファクタリングしばらくは関数にループし、要素が

を発見されたときに返します
function doSomething() { 
    while(something) { 
     if (this == key) { 
      return; 
     } 
    } 

    while(somethingelse) { 
     if (this == key) { 
      return; 
     } 
    } 

    while(somethingthird) { 
     if (this == key) { 
      return; 
     } 
    } 
} 
0

機能を使用し

function findSpecificElement($element) 
{ 
    while ($something) { 
     if ($something == $element) { 
     return $something; 
     } 
    } 

    while ($something) { 
     if ($something == $element) { 
     return $something; 
     } 
    } 

    ... 
} 
-1

gotoを実行すべきではありませんwhileループの上にジャンプして、このような状況で使用することができます。

while(something) { 
    if (this = key) { 
     goto yourDoom; // Breaks out of loop and goes to label "yourDoom" 
    } 
} 
while(somethingelse) { 
    if (this = key) { 
     goto yourDoom; // Breaks out of loop and goes to label "yourDoom" 
    } 
} 
while(somethingthird) { 
    if (this = key) { 
     goto yourDoom; // Breaks out of loop and goes to label "yourDoom" 
    } 
} 
yourDoom: // This is a label that you can go to 
// Do something 
+1

gotoを使用することは決してお勧めできません。その結果、コードを辿るのが難しくなります。 http://stackoverflow.com/questions/1900017/is-goto-in-php-evil – Pachonk

+0

@Pachonkこれは追いつくのが難しいことにも近くない。 PHPの 'goto'はC言語のような他の言語と同じ問題を抱えていませんが、C言語を使用すると深刻な問題を引き起こす可能性があります。それは人々が同じことのために2つを間違えないように何か異なる名前を付けられていたはずです。 –

関連する問題