Reputation: 31
I am looking for an element in multiple while loops, but if the element is found, I don't need to check the following while loops. How can I achieve something like this?
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.
}
}
Upvotes: 1
Views: 121
Reputation: 13283
goto
can be used in a situation like this to jump over the while
loops that should not be run.
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
Upvotes: -1
Reputation: 372
More correct to use php operator: continue, see:
http://php.net/manual/en/control-structures.continue.php
Example:
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip even members
continue;
}
do_something_odd($value);
}
Operator: break; - break the loop http://php.net/manual/en/control-structures.break.php
while(something) {
if (this == key) {
break;
}
}
Upvotes: 0
Reputation: 1316
Use a function
function findSpecificElement($element)
{
while ($something) {
if ($something == $element) {
return $something;
}
}
while ($something) {
if ($something == $element) {
return $something;
}
}
...
}
Upvotes: 0
Reputation: 6288
Refactor the while loops to a function and return when the element is found
function doSomething() {
while(something) {
if (this == key) {
return;
}
}
while(somethingelse) {
if (this == key) {
return;
}
}
while(somethingthird) {
if (this == key) {
return;
}
}
}
Upvotes: 2
Reputation: 18279
Use a variable (boolean) that knows if your condition was checked in the previous while, like this:
$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.
}
}
Upvotes: 3