Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: go back to the start of loop using a sort of 'break'?

Hi i have a loop and i was wondering if there was a command that you can jump back to the start of the loop and ignore the rest of the code in the loop

example:

for ($index = 0; $index < 10; $index++) 
{
    if ($index == 6)
        that command to go the start of the loop

    echo "$index, ";
}

should output

1,2,3,4,5,7,8,9 and skip the six

sort of same result as

for ($index = 0; $index < 10; $index++) 
{
    if ($index != 6)
        echo "$index, ";
}

is there a command for that?

thanks, matthy

like image 948
matthy Avatar asked Dec 03 '22 10:12

matthy


2 Answers

The keyword to use is continue:

for ($index = 0; $index < 10; $index++) 
{
    if ($index == 6)
        continue; // Skips everything below it and jumps to next iteration

    echo "$index, ";
}

As an aside, to get your desired output your for line should read this instead (unless you missed zero):

for ($index = 1; $index < 10; $index++) 
like image 113
BoltClock Avatar answered Dec 25 '22 21:12

BoltClock


Yes, continue advances to the next iteration.

like image 34
Oliver Charlesworth Avatar answered Dec 25 '22 23:12

Oliver Charlesworth