Home  >  Article  >  Backend Development  >  How to break the outer loop within the inner loop

How to break the outer loop within the inner loop

WBOY
WBOYforward
2024-02-09 10:12:29621browse

How to break the outer loop within the inner loop

When writing complex nested loops, sometimes we need to break the outer loop in the inner loop to end the entire loop process early. However, in PHP, loop structures do not directly support this operation. Therefore, PHP editor Xigua will share with you some methods and techniques to achieve the need to break the outer loop in the inner loop. Whether it is using labels and goto statements, or using auxiliary variables and conditional judgments, this article will provide you with a comprehensive solution. Come and take a look!

Question content

for i := 0; i < 5; i++ {
        fmt.Println("i is", i)
        for j := 0; j < 3; j++ {
            if j == 2 {
                break
            }
            fmt.Println("j is ", j)
        }
    }

I want this code to interrupt the program if i equals 2. How do I signal that I want to interrupt the outer loop within the inner loop?

I don’t know how to interrupt or continue the outer loop

Solution

outerLoop:
    for i := 0; i < 5; i++ {
        for j := 0; j < 3; j++ {
            if i == 3 {
                break outerLoop
            }
            fmt.Println(i, j)
        }
    }

This is the answer. You can use labels in go to reference different loops

The above is the detailed content of How to break the outer loop within the inner loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete