Search code examples
phploopserror-handlinggoto

Replace goto into while loop?


I am using goto if there is any error and it would start again at the top.

I also can't use goto in the function to jump outside of the function.

I know goto is bad but how would while loop would fit into my code?

For example:

$ch = curl_init();

retry:

$result = curlPost($ch, "home.php", http_build_query($arg));

if (strpos($postResult, "Welcome") !== false) {
    sleep(10);
    goto retry;
}

$sql = "SELECT * FROM data";
$q = mysql_query($sql) or die(mysql_error());

while($row =  mysql_fetch_assoc($q)) {
    $name['something'] = $row['name'];
    submitData($ch,$name);
}


function submitData($ch,$name) {

    $result2 = curlPost($ch, "submit.php", http_build_query($name));

    if (strpos($postResult, "Website close") !== false) {
        sleep(10);
        goto retry; //goto wouldnt work.
    }

   // do something here
}

Solution

  • Basically, you would have something like this:

    $success = false;
    while(!$success) {
        // do stuff here
        // psuedocode follows:
        if failure {
            continue; // skip remainder of `while` and retry
        }
        if complete {
            $success = true; // loop will end
            // or "break;" to exit loop immediately
        }
    }
    

    Just be aware that if your "if failure" is itself inside a loop, you will need continue 2;. Or if you're in a nested loop, continue 3; and so on.