Loop controllers

Loop controller are used to control the execution inside a loop. Includes:

  • Break

  • Continue

You can use loop controllers to control the loop flexibly.

Break

Break command will break current loop

Ex: : Find first Bob in an array, which is a names list. Since we don’t need find continue after 1st Bob, we could use break after we found one.

$list : [“Annie”,”Bob”, “Bob”, “Sabrina”]

$i : 1

@echo “Positions of Bob in list:\n”

while $i <= 4

    if $list[$i] = Bob:

        @echo $i . “\n”

        break

    $i++

> Positions of Bob in list:

> 2

Bob at position 2 is ignored

You could break outer loop using break <number>. With number is the outer-level number of the loop to be break. If you want to break parent loop, use break 2; if you want to break grand parent loop, use break 3; …

Ex: Find 1st Bob in an array, which is a names table.

$table :[ …

[“Jack”, “Daniel”, “Bill”, “Sabrina”],…

[“Annie”, “Bob”, “John”, “William”],…

[“Mike”, “Muriel”, “Bob”, “Brittney”]…

]

foreach $table as $i $row

    foreach $row as $j $name

        if $name = “Bob”

            @echo “Found first Bob at row “.($i+1).”, column “.($j+1)

            break 2

> Found first Bob at row 2, column 2

Continue

To skip the current loop and continue next loop

Ex: Find all Bob in an array, which is a names list.

$list : [“Annie”,”Bob”, “Bob”, “Sabrina”]

$i : 1

@echo “Positions of Bob in list:\n”

while $i <= 4

    if $list[$i] != Bob

        $i++

        continue

    @echo $i . “\n”

    $i++

> Positions of Bob in list:

> 2

> 3

When $list[$i] is not Bob, @echo $i . “\n” won’t be executed.

You could also use continue <number> to skip the containing outer loops, like with break.

Ex: There is an array, each line has only 1 Bob. Find Bob of each line, which is a names table.

$table :[…

[“Jack”, “Daniel”, “Bill”, “Sabrina”],…

[“Annie”, “Bob”, “John”, “William”],…

[“Mike”, “Muriel”, “Bob”, “Brittney”]…

]

foreach $table as $i, $row

    for $row as $j $name

        if $name != “Bob”

            @echo “Found Bob at row “.($i+1).“, column “.($j+1)

            continue 2

> Found Bob at row 2, column 2

> Found Bob at row 3, column 3