0

Say, for example, I have these parameters set for a for loop:

$b = 5;  
for ($a = 0; $a < $b; $a++) {  
    echo "Looped.";
}

Would there be a way to specifically target one of the looping instances (for this let's just say the 3rd loop) and skip it?

3
  • that should be a semicolon not a comma Commented Oct 27, 2016 at 1:41
  • @nogad haha wow, I can't believe I just did that. Commented Oct 27, 2016 at 1:51
  • you and the answers (guess they dont test) Commented Oct 27, 2016 at 1:52

3 Answers 3

4

You can use continue. For example:

$b = 5;  
for ($a = 0; $a < $b; $a++) { 
    if ($a === 3) {
        continue;
    } 
    echo "Looped.";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was looking for a solution because I knew it was possible in other programming languages but I wasn't having any luck.
1

This will do the same as well.

$b = 5;  
for ($a = 0; $a < $b; $a++) { 
    if ($a != 3) {
        echo "Looped.";
    }
}

2 Comments

Hey, that also makes a lot of sense. Thanks! It didn't even cross my mind to do that.
Definitely the most simple solution.
0

or you could simply use a while loop

$a = 0; $b = 5;  
while($a < $b && $a !=3 ){ 
    echo "Looped.";
    $a++;
}

1 Comment

Never knew there would be so many simple solutions to this. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.