shantanuo
shantanuo

Reputation: 32336

exit for loop with echo

The following PHP code is working as expected. I need to echo "copy error" message when the code is unable to execute the command in 4 attempts.

for($num_tries = 0 ; $num_tries < 4 ; $num_tries++)
{
    $cloudcmd = "cp abc xyz ";
    system($cloudcmd,$status);
    if($status != 0)
    {
        sleep(3) ;
        continue ;
    }
    break ;
}

I tried to add echo command after break; but it does not seem to work.

Upvotes: 3

Views: 1264

Answers (5)

Ritika  Jain
Ritika Jain

Reputation: 64

<?php  
for($num_tries = 1 ; $num_tries <=4 ; $num_tries++){  
    $cloudcmd = "cp abc xyz ";  
    system($cloudcmd,$status);  
    if($status != 0) {  
       if($num_tries!=4){  
         sleep(3);  
         continue;  
       } else {  
         echo "error";  
       }  
    }                               
    break;  
}
?>

Upvotes: 1

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

Try doing this:

for ($num_tries=0;$num_tries < 4;$num_tries++)
{
    system('cp abc xyz',$status);
    if ($status === 0)
    {
        break;
    }
    sleep(3);
}
if ($status !== 0)
{
    echo 'error';
}

This loop will break as soon as $status is 0, meaning the system() call was a success, after the loop, the $status value will be accessible, still (PHP doesn't have block scope), so check it's value and echo if needed. You can easily replace the echo statement using an exit(), to stop the rest of the script.

Upvotes: 1

zaf
zaf

Reputation: 23264

Strictly, you don't need to introduce additional variables and checks to do this.

Keeping it simple, you can inspect the value of the for loop variable $num_tries once outside the for loop:

if($num_tries==4)....

You also have the $status variable available after the for loop.

if($status!=0)....

Upvotes: 2

Ayush
Ayush

Reputation: 42450

A break statement causes the loop to break, and any code that occurs after the break, within the loop is skipped over.

Perhaps, you could do something like this:

$success = false;

for($num_tries = 0 ; $num_tries < 4 ; $num_tries++) {

    if (success()) {
        // do something
        $success = true;
    }
}

echo ($success) ? 'Success' : 'Failure';

Upvotes: 0

Tschallacka
Tschallacka

Reputation: 28742

$success = false;
for($num_tries = 0 ; $num_tries < 4 ; $num_tries++)
        {
        $cloudcmd = "cp abc xyz ";
        system($cloudcmd,$status);
        if($status != 0)
            {
            sleep(3) ;
            continue ;
            }
    $success=true;
    break ;
    }
if($success)
    {
    //do your thing
    }

Upvotes: 1

Related Questions