Break out of unknown number of nested loops without using go to?

4077 views php
7

I am writing some code which will frequently contain loops that I need to break out of under certain conditions. The problem is that sometimes, I am nested 3 levels deep, some times 4 and some times 5 or more.

I could break out by writing break 3, break 4 and break 5 etc. but that requires me to keep track of the number of nested loops. Is their an easier way of breaking out of unknown number of nested loops without using goto?

answered question

Possibly breaking up the code into a separate function which can return when needed?

why not put them in a function and break out by using return?

I can't think of any reason the answer wouldn't be "refactor your code so that you never need anything besides break, continue ... or return.

return will get you out of a function, or you can throw a special type of exception and catch only exceptions of that type. Programming is usually considered binary, but there's always the 3rd state: exceptions, unknown, undefined, no answer, etc.

How can the number of nested loops be unknown? Does the loop you need to break out of determined dynamically?

@Barmar It know the value but it is different for 80 different sections of code and using break number requires me to count the loops every time. I was looking of a more unified way of doing things so that I need to write the breaking out line only once. :)

1 Answer

0

If you know the depth of the loop you want to break out of, but not how many levels down you are from that, you can use a variable that each loop checks.

$break_level = 99;
while (...) {
    while (...) {
        while (...) {
            while (...) {
                ...
                if (...) {
                    $break_level = 2;
                    break;
                }
                ...
            }
            if ($break_level <= 3) {
                break;
            }
        }
        if ($break_level <= 2) {
            break;
        }
    }
    if ($break_level <= 1) {
        break;
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.