Break the loop from other function/method/something...?

Viewed 73

Is it possible to break the loop using inside function/method or something else?

Assume this code:

do {
    $page = $this->get_page($this->profile_link . '&page=' . $page_count);

    if ($this->pageNotExists($page, 'has no public')) {
         break;
    }

    $links = array_merge($links, $this->get_videos_from_given_page($page));

    $page_count++;
} while (1);

I would like to take this part:

if ($this->pageNotExists($page, 'has no public')) {
    break;
}

And make from this re-usable method/function or something that will make break here.

I just don't like this portion of code to be in here.

And I have other methods that use the same portion of code. It's a code duplication and I don't like it.

So is it possible to extract this code to function/method or something, take it out of here

if ($this->pageNotExists($page, 'has no public')) {
    break;
}

While still having the same result and having all work the same?

2 Answers

A break statement that is in the outer part of a program (e.g. not in a control loop) will end the script. This caught me out when I mistakenly had a break in an if statement

i.e.

<?php 
echo "hello";
if (true) break;
echo " world"; 
?>

will only show "hello"

There is no way to directly accomplish what you are asking for. The flow of the code should be clear. A function should not be able to interrupt it, unless it throws an exception.

You might want to move the logic directly into the loop condition.

while ($page = $this->getPageByPageCount($page_count)) {
    ...
}

with getPageByPageCount being defined as such:

private function getPageByPageCount($page_count) {
    $page = $this->get_page($this->profile_link . '&page=' . $page_count);
    if (!pageCheck($page)) {
        return null;
    }
    return $page;
}
Related