Onitech
Onitech

Reputation: 85

Is there a way to break a loop from other method?

I tried to refactor some nested loop with nested if code then I segregate one of the nested if and created its own method.

any tips and tricks to refactor this type of code is much appreciated.

note: these are only example, the original code has a lot of nested loop and nested if.

previous code:

function bar()
{
    $is_baz = 'BAZ';
    $is_bas = 'BAS';

    while (TRUE) {
        echo 'Im';

        if ($is_baz == 'BAZ') {
            if ($is_bas == 'BAS') {
                echo 'here';
                break;
            } else {
                echo 'not here';
            }
        }

        echo '!!!';
        break;
    }

    echo 'too';
}

refactored code:

function foo($is_bas)
{
    if ($is_bas == 'BAS') {
        echo 'here';
        break;
    } else {
        echo 'not here';
    }
}

function bar()
{
    $is_baz = 'BAZ';
    $is_bas = 'BAS';

    while (TRUE) {
        echo 'Im';

        if ($is_baz == 'BAZ') {
            foo($is_bas);
        }

        echo '!!!';
        break;
    }

    echo 'too';
}

expected result: Imheretoo

Upvotes: 0

Views: 49

Answers (2)

Luna
Luna

Reputation: 2322

function foo($is_bas)
{
    if ($is_bas == 'BAS') {
        echo 'here';
        return true;
    }
    echo 'not here';
    return false;
}

function bar()
{
    $is_baz = 'BAZ';
    $is_bas = 'BAS';

    while (TRUE) {
        echo 'Im';

        if ($is_baz == 'BAZ' && foo($is_bas)) {
            break;
        }

        echo '!!!';
        break;
    }

    echo 'too';
}

bar();

Upvotes: 0

Nick
Nick

Reputation: 147206

You can't directly break an outer loop from inside a function but you can return a value that tells the outer loop to break:

function foo($is_bas)
{
    if ($is_bas == 'BAS') {
        echo 'here';
        return true;
    }
    return false;
}

function bar()
{
    $is_baz = 'BAZ';
    $is_bas = 'BAS';

    while (TRUE) {
        echo 'Im';

        if ($is_baz == 'BAZ') {
            if (foo($is_bas)) break;
        }

        echo '!!!';
        break;
    }

    echo 'too';
}

bar();

Output:

Imheretoo

Upvotes: 1

Related Questions